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

#define VER             "1.00"

string 
    home;

void gethome (list envp)
{
    int
        i;
    for (i = 0; i < sizeof (envp); i += 2)
        if (element (i, envp) == "BACKUP_HOME")
	{
	    home = element (i + 1, envp);
	    return;
	}
	
    printf ("list: Environment variable BACKUP_HOME undefined!\n"
            "Either define that variable or use the backup script.\n");
    exit (1);	    
}

string maketemp ()
{
    return ("/tmp/" + "list." + (string) getpid ());
}

void main (int argc, list argv, list envp)
{
    list
        fulllist;
    string
        volume,
        tmpfile,
        full,
	incremental,
        pattern;
    int
        i;
	
    echo (0);
    
    if (argc > 2)
    {
        printf ("\n"
	        "ICCE Backed Up Files Lister  V" VER "\n"
	        "Copyright (c) ICCE 1994. All rights reserved.\n"
		"\n"
		"list by Karel Kubat.\n"
		"\n"
		"Usage: list [pattern]\n"
                "Searches in the lists of backed up files for anything "
		                                "that matches the\n"
                "pattern. If no pattern is given, \"*\" (all files) is "
		                                "assumed.\n"
                "\n");
        exit (1);
    }
    
    gethome (envp);
    
    if (argc == 2)
        pattern = "'^" + element (1, argv) + "'";
	
    chdir (home + "/lists");	
    if (! (fulllist = makelist ("*.full")) )
    {
        printf ("list: You don't even have full backups.\n");
	exit (1);
    }
    
    tmpfile = maketemp ();
    
    for (i = 0; i < sizeof (fulllist); i++)
    {
        full = element (i, fulllist);
	incremental = change_ext (full, ".incremental");
	volume = change_ext (full, "");
	
	if (pattern)
	{
	    if (! exec (P_NOCHECK, "egrep", pattern, 
	        full, ">", tmpfile)
	       )
	    {
	        printf ("Full backup of volume ", volume, ":\n");
		exec ("cat", tmpfile);
	    }
	    if (exists (incremental) &&
	        ! exec (P_NOCHECK, "egrep", pattern, 
	        incremental, ">", tmpfile)
	       )
	    {
	        printf ("Incremental backup of volume ", volume, ":\n");
		exec ("cat", tmpfile);
	    }
	}
	else
	{
	    printf ("Full backup of volume ", volume, ":\n");
	    exec ("cat", full);
	    if (exists (incremental) && (int) element (1, stat (incremental)))
	    {
	        printf ("Incremental backup of volume ", volume, ":\n");
                exec ("cat", incremental);
	    }
	}
	    
    }

    exec ("rm", "-f", tmpfile);
    exit (0);
}
