#!/usr/local/bin/icmake -qi

#define VER             "1.00"

string makegrep (string file)
{
    string
        line,
	ret;
    list
        input,
	stripped;
     int
        i;
	
    while (input = fgets (file, (int) element (1, input)))
    {
        stripped = strtok (element (0, input), " #\t\n");
        line = element (0, stripped);
        if (line && element (0, line) != "#")
	{
	    if (ret)
	        ret += "|";
	    ret += "^" + line;
	}
    }
    
    return (ret);
}    

void main (int argc, list argv)
{
    string
        startdir,
	startdirfile,
	excludefile,
	listfile,
	stampfile,
	grepcmd;
    list
        finfo;
	
    echo (0);
    
    if (argc < 4 || argc > 5)
    {
        printf ("\n"
	        "ICCE Backup Filelist Builder V" VER "\n"
		"Copyright (c) ICCE 1994. All rights reserved.\n"
		"\n"
		"buildlist by Karel Kubat.\n"
		"\n"
                "Usage: buildlist startdirfile excludefile listfile "
		                                        "[stampfile]\n"
		"where:\n"
		"       startdirfile : file holding directory to start scanning\n"
		"       excludefile  : file holding directories to exclude\n"
		"       listfile     : file to receive listing of these files\n"
		"       stampfile    : (optional) stamp of last run\n"
		"\n"
                "A list of files to backup is built, the files are at and "
		                                "under the\n"
                "directory whose name is contained in the startdirfile.\n"
                "The output is sent to listfile. Only the directories which "
		                                "do not appear\n"
                "in the excludefile are scanned.\n"
                "If stampfile is present, only files younger than the stamp "
		                                "are taken.\n"
                "\n");
        exit (1);
    }
    
    startdirfile = element (1, argv);
    finfo = fgets (startdirfile, 0);
    startdir = element (0, strtok (element (0, finfo), " \t\n"));
    
    if (! startdir)
    {
        printf ("buildlist: no startdir to be found in the file ", 
	        startdirfile, "\n");
        exit (1);		
    }
    
    excludefile = element (2, argv);
    listfile = element (3, argv);
    if (argc == 5)
        stampfile = element (4, argv);
	       
    grepcmd = makegrep (excludefile);
     
    printf ("Building list of files.. have patience..\n");
     
    if (stampfile)
        exec (P_NOCHECK, "find", startdir, "-newer", stampfile, 
              "| egrep -v", "'" + grepcmd + "'", ">", listfile);
    else
        exec (P_NOCHECK, "find", startdir,
              "| egrep -v", "'" + grepcmd + "'", ">", listfile);
	      
    printf ("List of files built.\n");    	      

    exit (0);
}
