/* @(#)post_update.c 1.6 95/09/16 */

/*
 * Copyright (c) 1994, 1995 by Wayne C. Gramlich.  All rights reserved.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * for any purpose is hereby granted without fee provided that the above
 * copyright notice and this permission are retained.  The author makes
 * no representations about the suitability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 */

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

#include "config_extern.h"
#include "error_extern.h"
#include "link_extern.h"
#include "local_extern.h"
#include "form_extern.h"
#include "remote_extern.h"
#include "vector_extern.h"

/*
 * main()
 *	This program will process an update form request.
 */
int
main(
    int argc,
    char **argv)
{
    FILE *annote_file;
    Config config;
    Errors errors;
    Link link;
    Links links;
    Text submit_text;
    Str remote_url_str;
    Remote remote;

/* For debugging :
    FILE *debug_file;

    debug_file = fopen("/tmp/debug", "a");
    if (debug_file != (FILE *)0) {
	(void)fprintf(debug_file, "post_update main() called!\n");
	(void)fflush(debug_file);
    }
*/

    annote_file = stdout;
    (void)fprintf(annote_file,
      "Content-type: text/html\n"
      "\n"
      "<HTML>\n"
      "<Head>\n"
      "<Title>\n"
      "Update Response\n"
      "</Title>\n"
      "</Head>\n"
      "<Body>\n");
    (void)fflush(annote_file);

    errors = errors_create();
    config = config_create(errors);
    if (errors_size(errors) != 0) {
	goto errors_return;
    }
    if (argc > 1) {
	/* Local test */
	remote_url_str = (Str)argv[1];
    } else {
	submit_text = form_post_read(errors);
	remote_url_str = form_get_value(submit_text, (Str)"RefURL", errors);
    }
    (void)fprintf(annote_file,
      "<!-- Remote URL: `%s' -->\n",
      remote_url_str);
    (void)fflush(annote_file);

    if (errors_size(errors) != 0) {
	goto errors_return;
    }
    remote = remote_scan(remote_url_str, config, errors);
    links = remote_links(remote);
    LINKS_LOOP(link, links) {
	local_update(link_href(link), remote, config, errors);
    }
    if(errors_size(errors) != 0) {
	goto errors_return;
    }
    (void)fprintf(annote_file,
      "<!-- Status: 0 -->\n"
      "The following documents were updated as a result of scanning\n"
/**/  "<A HRef=\"%s\">\n"
/**/  "%s</A>:\n",
      remote_url_str, remote_url_str);
    remote_write(remote, stdout, config);
    (void)fprintf(annote_file, "</Body>\n");
    (void)fprintf(annote_file, "</HTML>\n");
    (void)fflush(annote_file);
    return 0;
  errors_return:
    errors_write(errors, stdout, 1);
    (void)fprintf(annote_file, "</Body>\n");
    (void)fprintf(annote_file, "</HTML>\n");
    (void)fflush(annote_file);
    return 1;
}




