#! /usr/bin/perl

#______________________________________________
# FILE NAME     : trackFiles.pl
# AUTHOR        : vAchA (http://www.cs.utexas.edu/~vacha)
# DESCRIPTION   : This script tracks the change in the watchlist files by 1.unix modified timestamp 2. file Size
# DATE CREATED  : 03/15/2010
# RELATED FILES : writes 1. tsSummary to detect change from last run 
# COMPILER      : Perl 
# COMMENTS      :
# INPUT         : watchList <a file containing a list of files, one per line>
# OUTPUT        :
# CONTACT       : vacha@cs.utexas.edu
#______________________________________________

use strict;
use Getopt::Long;
use Time::localtime;

#var declaration begins
my $fileName = "";
my @files;
my $watchList = "watchList";
my $timestampFile = "tsSummary";
my %hashTime = ();
my %hashSize = ();
#var declaration ends


# check if we have the right input and get it
# default watchList name is watchList
if( $#ARGV == 1 )
{

    GetOptions( "watchList:s" => \$watchList);    
}

# read the watchList 
if(-e $watchList)
{
    open(LIST_FP,"<$watchList");
    @files = <LIST_FP>;
    chomp(@files);
    close(LIST_FP);
}
else
{
    die "$watchList does not exist\n";
}

# now read the timestamps
if(-e $timestampFile)
{
    #read timestamp info into hash
    open(IN_FP,"<$timestampFile");
    my @timingInfo = <IN_FP>;
    close(IN_FP);

    foreach my $line (@timingInfo)
    {
	my ($name, $size, $stamp) = split(" ",$line);
	$hashSize{$name} = $size;
	$hashTime{$name} = $stamp;
	
    }
    
    open(OUT_FP,">$timestampFile");
    # now compare with the new info
    foreach my $file (@files)
    {
	#read inode info
	if(-e $file)
	{
	    #print "reading info about $file...";
	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)= stat($file);
	    print OUT_FP "$file $size $mtime\n";
	    if(exists $hashTime{$file})
	    {
		if($hashTime{$file}== $mtime)
		{
		    print "$file UNCHANGED with $size bytes\n";
		}
		else
		{
		    my $oldSize = 0;
		    if(exists $hashSize{$file})
		    {
			$oldSize = $hashSize{$file};
		    }
		    my $dateString = ctime($mtime);
		    print "$file HAS CHANGED from $oldSize to $size bytes at $dateString\n";
		}
	    }
	    else
	    {
		print "$file UNWATCHED. Added for future\n";
	    }
	}
	else
	{
	    print "$file not found. Skipping..\n";
	}
    }
    close(OUT_FP);
}
else
{
    #we create the timestamp file for first use
    print "$timestampFile not found. Creating timeStamp summary for all the files...\n";    
    open(OUT_FP,">$timestampFile");
    foreach my $file (@files)
    {
	#read inode info and store
	if(-e $file)
	{
	    print "reading info about $file...";
	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks)= stat($file);
	    print OUT_FP "$file $size $mtime\n";
	    print "done\n";
	}
	else
	{
	    print "$file Not found. Skipping..\n";
	}
    }
    print "Summary complete\n";
    close(OUT_FP);
}


