#!/usr/bin/perl
##############################
#                            #
#     Web Page Monitor       #
#     ----------------       #
#                            #
#        by [duke]           #
#                            #
##############################

# wpm.pl -- usage: wpm.pl <html file> [log file]
# this program adds cgi to a html file that logs each time
# a page is accessed and by whom. note that the file this 
# generates should be in a dir where CGI can be executed

# greetz to banshee, fh_(still mah g0d !@#), tm, evry1 at #sinnerz,
# GRENd3l, kryse (aka df1), eprom, kinetic, mudweg, and k0n inc.

$file = $ARGV[0];
if ($file eq ""){
    print "You must specify a html file to convert!\n";
} else {
    if ($file =~ /\.htm/){
	print "\nWeb Page Monitor!\n";
	print "-----------------\n";
	print "\n\nAdding cgi to file...\n";
	if (-e $file){
	    if ($ARGV[1] eq ""){
		print "Please specify the full path of the logfile you want this page to log to: ";
		$logfile = <STDIN>;
		chop($logfile);
	    } else {
		$logfile = $ARGV[1];
	    }
	    open(FHANDLE, $file);
	    @array = <FHANDLE>;
	    close FHANDLE;
	    @newfile = split(/\./, $file);
	    $file = $newfile[0] . ".cgi";
	    while (-e $file){
		print $file, " already exists!\n";
		print "Please specify an alternate name for the output file: ";
		$file = <STDIN>;
		chop($file);
	    }
	    print "Generating output file ", $file, "..\n";
	     open(FHANDLE, ">$file");
	    print FHANDLE "#!/usr/bin/perl\n";
	    print FHANDLE "print \"Content-type: text/html\\n\\n\";\n";
	    print FHANDLE "if (!(-e \"$logfile\")){\n";
	    print FHANDLE "\tsystem(echo \"        wpm logfile\\n\\n\");\n";
	    print FHANDLE "\tchmod 0766, '$logfile';\n";
	    print FHANDLE "\topen(LOG, \">$logfile\");\n";
	    print FHANDLE "\tprint LOG \" Logfile for $file\\n\";\n";
            print FHANDLE "\tprint LOG \"------------------------\\n\\n\\n\";\n";
	    print FHANDLE "\tclose LOG;\n";
	    print FHANDLE "}\n";
            print FHANDLE "open(LOG, \">>$logfile\");\n";
	    print FHANDLE "while((\$head, \$tail) = each(%ENV)){\n";
	    print FHANDLE "\t\$line = \$head . \"=\" . \$tail;\n";
	    print FHANDLE "\tif(\$head =~ /HTTP_USER_AGENT/ || \$head =~/REMOTE/){\n";
	    print FHANDLE "\t\tpush(\@logz, \$line);\n";
	    print FHANDLE "\t}\n";
	    print FHANDLE "}\n";
	    print FHANDLE "foreach \$output (\@logz){\n";
	    print FHANDLE "print LOG \$output, \"\\n\";\n";
	    print FHANDLE "}\n";
	    print FHANDLE "close LOG;\n";
	    foreach(@array){
		s/\s/ /g;
		s/\"/\\"/g;
		print FHANDLE "print \"$_\\n\";\n";
	    }
	    close FHANDLE;
	    chmod 0755, "$file";
	} else {
	    print "File doesn't exist!\n";
	}
    } else {
	print "incorrect file type! Must be a html file!\n";
    }
}










