#include	<stdio.h>
#include	<string.h>
#include	"xgroups.h"

int cut_string(char *buffer, char *s,char *cs)
{
	if (strstr(s,cs)==NULL) return (-1);
	strcpy(buffer,strstr(s,cs)+strlen(cs));
	if (strchr(buffer,'\"') != NULL) *(strchr(buffer,'\"'))='\0';
	return(0);
}

int esiste(char *fn)
{
	FILE *fd;
    if ( (fd=fopen(fn,"rt")) == NULL) return(0);
	fclose(fd);
	return(1);
}

main(int argc, char *argv[])
{
	char filename[PATH_MAX];
	char fn[PATH_MAX];
	char cmd[PATH_MAX];
	FILE *fd;
	char s[PATH_MAX];
	char n[PATH_MAX];
	char i[PATH_MAX];
	char c[PATH_MAX];

	strcpy(filename,BOOTGRP);

	sprintf(fn,"./%s.grp",filename);
    if (!esiste(fn))
    {
		sprintf(fn,"%s/.xgroups/%s.grp",getenv("HOME"),filename);
    	if (!esiste(fn))
		{
			sprintf(fn,"%s/%s.grp",GRPDIR,filename);
    		if (!esiste(fn))
			{
				fprintf(stderr,"cannot open group %s\n",filename);
				exit(1);
			}
		}
	}

	fd=fopen(fn,"rt");
	if (fd==NULL)
	{
		fprintf(stderr,"Errore aprendo il gruppo %s\n",fn);
		exit(1);
	}

	while(1)
	{
		fgets(s,sizeof(s),fd); if (s[0]=='#') continue;

		if ((strstr(s,"N=\"")!=NULL) || (strstr(s,"G=\"")!=NULL))
		{
			cut_string(n,s,"N=\"");
			cut_string(i,s,"I=\"");
			
			if (strstr(s,"G=\"")!=NULL)
			{
				cut_string(c,s,"G=\"");
			}
			else
			{
				cut_string(c,s,"C=\"");
			}

			sprintf(cmd,"%s &",c);

			if (system(cmd))
			{
				fprintf(stderr,"%s: cannot execute %s\n",argv[0],c);
			}
		}
		if (feof(fd)) break;
	}

	fclose(fd);
}
