/*---[ scriptwriter.c ]-----------------------------------------------
 * Copyright (C) 2000 Tomas Junnonen (majix@sci.fi)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Creates the firewall script, based on wizard selections.
 *--------------------------------------------------------------------*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>


#include "firestarter.h"
#include "druid.h"
#include "druid-choices.h"
#include "scriptwriter.h"
#include "modify_ipup.h"
#include "netfilter-script.h"
#include "ipchains-script.h"

extern gboolean NETFILTER;

/*---[ check_file ]---------------------------------------------------
 * Check that file exists, if not, create
 *--------------------------------------------------------------------*/
static void
check_file (gchar *path)
{
    FILE *file = NULL;
	if ((fopen (path, "r") == NULL) && (errno == ENOENT)) {
        if ((file = fopen (path, "w")) != NULL) {
		chmod (path, 00700);

		fprintf (file, "#!/bin/sh\n");

		fclose (file);
        }
	}
}

/*---[ create_modrules_files ]----------------------------------------
 * Create the empty modrules scripts, unless already exists.
 *--------------------------------------------------------------------*/
static void
create_modrules_files (void)
{
	gchar *allow_allpath = FIRESTARTER_RULES_DIR "/firestarter/allow-all";
	gchar *deny_allpath = FIRESTARTER_RULES_DIR "/firestarter/deny-all";
	gchar *allow_service_machinepath = FIRESTARTER_RULES_DIR "/firestarter/allow-service-machine";
	gchar *allow_service_allpath = FIRESTARTER_RULES_DIR "/firestarter/allow-service-all";

	check_file (allow_allpath);
	check_file (deny_allpath);
	check_file (allow_service_machinepath);
	check_file (allow_service_allpath);
}

/*---[ write_script ]-------------------------------------------------
 * Creates the shell script, called when the finish button is pressed
 *--------------------------------------------------------------------*/
void
write_script (GnomeDruidPage *druidpage, gpointer druid, Druid *data)
{
	if (NETFILTER)
		write_netfilter_script (data);
	else
		write_ipchains_script (data);

	create_modrules_files ();
	restart_firewall ();
	save_choices (data);

	if (gnome_config_get_bool ("/firestarter/Druid/startonppp=FALSE"))
		modify_ipup (TRUE);
	else
		modify_ipup (FALSE);
}
