%(c_comment template "header_gpl")

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cgi.h>
#include <appliance-config.h>

static void _create_script_lockfile()
{
	if (creat(SCRIPT_LOCKFILE, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
	    == -1) {
		cgiError("Error creating " SCRIPT_LOCKFILE);
	}
}

static void _wait_on_script_lockfile(char *hostname)
{
	printf("<HTML>\n");
	printf("<HEAD>\n");
	printf("<TITLE>Saving Configuration</TITLE>\n");
	printf
	    ("<meta http-equiv=refresh content=\"1; URL=%s\">\n",
	     get_wait_url(hostname));
	printf("</HEAD>\n");
	printf("<BODY>\n");
	printf("<p>Please wait as configuration is saved...</p>\n");
	printf("</BODY>\n");
	printf("</HTML>\n");
}

static void _notify_server(s_cgi *cgi)
{
	const char *service;
	FILE *serverfifo;
	const char *fifo_path = get_server_fifo_path();

	if ((serverfifo = fopen(fifo_path, "w")) == NULL)
		cgiError("Error opening server FIFO");

	if (NULL == (service = get_post_mode(cgi))) {
		cgiError("Error determining service name");
	}

	fprintf(serverfifo, "%s\n", service);

	if (fclose(serverfifo) == EOF)
		cgiError("Error closing server FIFO");
}

int main(int argc, char *argv[], char *env[])
{
	char *hostname;
	struct stat statbuf;

	cgiHeader();

	/* Make sure this is done BEFORE new config. saved.  Otherwise,
	 * hostname change will cause this to fail! */
	hostname = get_hostname();

	if (stat(SCRIPT_LOCKFILE, &statbuf) != -1) {
		_wait_on_script_lockfile(hostname);
	} else {

		const char *method = getenv("REQUEST_METHOD");
		if (NULL == method) {
			cgiError("no REQUEST_METHOD");
		}
	
		if (0 == g_strcasecmp(method, "GET")) {
			char *sidebar;

			sidebar = build_sidebar();

			print_form(sidebar);

		} else if (0 == g_strcasecmp(method, "POST")) {
			s_cgi *cgi;
			struct stat statbuf;
			const char *fifo_path = get_server_fifo_path();

			if (NULL == (cgi = cgiInit())) {
				cgiError("Error initializing CGI library");
			}

			if (stat(fifo_path, &statbuf) == -1) {
				cgiError("Server FIFO does not exist");
			}

			save_data(cgi);
			_create_script_lockfile();
			_notify_server(cgi);
			_wait_on_script_lockfile(hostname);

			cgiFree(cgi);

		} else
			cgiError("Unknown request method");
	}

	g_free(hostname);

	exit(EXIT_SUCCESS);
}
