/*---[ modify_ipup.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.
 *
 * Modifies the file /etc/ppp/ip-up.local based on wizard selections
 *--------------------------------------------------------------------*/

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


#include "modify_ipup.h"

void
modify_ipup (gboolean add)
{
	char *path = "/etc/ppp/ip-up.local";

	if (add) {
		if ((fopen (path, "r") == NULL) && (errno == ENOENT)) {
			FILE *file = fopen (path, "w");
			if (file != NULL) {
				chmod (path, 00700);
				fprintf (file, "/usr/bin/firestarter\n");
				fclose (file);
            		}
			return;
		}
		else {
			gchar buf[512];
			GList *list = NULL;
			GList *p;
			FILE *file = fopen (path, "r+");

            if (file != NULL) {
			chmod (path, 00700);

			while (fgets (buf, 512, file) != NULL) {
				if (strstr (buf, "/usr/bin/firestarter"))
					return;
				list = g_list_append (list, g_strdup (buf));
			}

			rewind (file);
			fprintf (file, "/usr/bin/firestarter/\n");

			p = list;
			while (p != NULL) {
				fprintf (file, p->data);
				p = p->next;
			}

			fclose (file);
		}
			return;
		}
	}
	else {
		if (fopen (path, "r")) {
		 	gchar buf[512];
			GList *list = NULL;
			GList *link = NULL;
			FILE *file = fopen (path, "r");
			gint pos = 0;
			chmod (path, 00700);

		if (file != NULL) {
			while (fgets (buf, 512, file) != NULL) {
				list = g_list_append (list, g_strdup (buf));
				if (strstr (buf, "/usr/bin/firestarter")) {
					printf ("Found at %d\n", pos);
					link = g_list_nth (list, pos);
				}
				++pos;
			}
			fclose (file);

			list = g_list_remove_link (list, link);

			file = fopen (path, "w");
			link = list;
			while (link != NULL) {
				fprintf (file, link->data);
				link = link->next;
			}

			fclose (file);
            }
			return;
		}
	}
}
