#include "stdhead.h"

void read_config_file (char **config_buff, char *file_name)
{
    int fd, n, size = 0;
    
    if ((fd = open (file_name, O_RDONLY)) == -1)
    {
	printf ("Error opening file %s.\n", file_name);
	exit (0);
    }
    
    (*config_buff) = (char *) realloc (*config_buff, 1);
    size = 1;

    while (read (fd, &(*config_buff)[size - 1], 1) > 0)
    {
	size++;
	*config_buff = (char *) realloc (*config_buff, size);
    }
    (*config_buff)[size - 1] = '\0';

    close (fd);
}
    
void skip_whitespace (char **curr_ptr)
{
    while ((**curr_ptr == ' ') || (**curr_ptr == '\t') || (**curr_ptr == '\r') || (**curr_ptr == '\n'))
	(*curr_ptr)++;
}

int move_across_substring (char **curr_ptr, char *substring)
{
    *curr_ptr = strstr (*curr_ptr, substring);
    if (*curr_ptr)
	*curr_ptr += strlen (substring);
    else
	return 0;
    return 1;
}

void read_token (char **token, char **curr_ptr)
{
    char *p;
    int n = 0;
    
    if (*token)
	*token = (char *) realloc (*token, 0);
    
    while ((**curr_ptr != ' ') && (**curr_ptr != '\t') && (**curr_ptr != '\r') && (**curr_ptr != '\n'))
    {
	n++;
	*token = (char *) realloc (*token, n);
	p = *token + (n - 1);
	*p = **curr_ptr;
	(*curr_ptr)++;
    }

    n++;
    *token = (char *) realloc (*token, n);
    p = *token + (n - 1);
    *p = '\0';
}


char ** get_all_interfaces (char * file_name, int * count)
{
    char ** interface = 0 , ** p = 0;
    char * buff = 0, * curr_ptr = 0, *token = 0;
    read_config_file (&buff, DEFAULT_SOLICIT_CONFIG_FILE);
    curr_ptr = buff;
    *count = 0;
    
    while (move_across_substring (&curr_ptr, "interface"))
    {
	skip_whitespace (&curr_ptr);
	read_token (&token, &curr_ptr);
	interface = (char **) realloc (interface, ++(*count) * sizeof (char *));
	p = interface + (*count) -1;
	*p = (char *) malloc (strlen (token) * sizeof (char));
	strcpy (*p, token);
    }
    return interface;
}


int main ()
{
    char ** interface, **p;
    int i , n;
    char command [100];
    pid_t child;
    
    interface = get_all_interfaces (DEFAULT_SOLICIT_CONFIG_FILE, &n);
    for (i = 0; i < n; i++)
    {
	p = interface + i;
	if ((child = fork ()) == 0)
	{
	    printf ("Fork for interface %s successful.\n", *p);
	    if (execlp ("cli", "cli", *p, (char *) 0) < 0)
		printf ("Exec for interface %s failed.\n", *p);
	    else
		printf ("Exec for interface %s successful.\n", *p);
	}
	else if (child == -1)
	    printf ("Fork for interface %s failed.\n", *p);
    }
    exit (0);
}

