#!/usr/bin/perl


############################################################################
# Define configuration constants                                           #
############################################################################

$REQUIRE_DIR = '/home/cvs/support/scripts';
$LOCK_DIR = '/tmp/';
$MAX_WAIT = 15;
$UPLOAD_LOCATION = "/repository/uploadedFiles/";
#$UPLOAD_LOCATION = "/tmp";

############################################################################
# Get Required subroutines which need to be included.                      #
############################################################################
push(@INC, $REQUIRE_DIR) if $REQUIRE_DIR;
close(STDERR);
eval <<end_eval;
require 'locksubs.pl';
end_eval

if ($@) {
   print "$@";
   exit;
}

############################################################################
# Read in the information from the STDIN and ARGS, parse the info          #
############################################################################
my $file_info = $ARGV[0];
my $user_id = $ARGV[1];
my @file_details=split(/\s,/,$file_info);
my $checkInPath = $file_details[0];
my %checkInFiles = ();
my $branch_name = "";
while(<STDIN>) {
	chomp($_);
	 if (m/(\d+)(?:\s+)?:(.*)/) {
                $bugId = $1;
                $message =$2;
                $message =~ s/^\s+//;
	}
}

############################################################################
# generating a time stamp
############################################################################
my $curtime=&getUploadTimeStamp;

############################################################################
# processing a hash (key -> value)
############################################################################
for ($i = 1; $i < @file_details; $i++) {
	($file_name,$cVersion,$branch_name) = split(/,/,$file_details[$i]);
	$checkInFiles{$checkInPath."/".$file_name} = $cVersion;
}

#####################################################################
# generate the uploaded file list xml based on the branch
#####################################################################
$uploadXMLFile = $UPLOAD_LOCATION."/uploadedFileList.xml.base"; # default to trunk
my $branch = length($branch_name);
if ($branch > 3) {
	$uploadXMLFile = $UPLOAD_LOCATION."/uploadedFileList.xml.".$branch_name;
}

#####################################################################
# locking the file 						    #
#####################################################################
if (&lock($uploadXMLFile, $LOCK_DIR, $MAX_WAIT)) {
    print "$Error_Message";
    exit;
}

####################################################################
# Processing starts
####################################################################
&printDebug();
use Fcntl qw (:flock);

# If bugid=30000, do not add to regular uploaded file
if ($bugId == "30000") {
    $tmpFile = $uploadXMLFile . "-30000";
    $uploadXMLFile = $tmpFile;
}
   
&addToUploadedFile($bugId,$message, $user_id, $checkInPath, %checkInFiles);

###############
# debug only
##############
sub printDebug {
	print "xml Name : $uploadXMLFile\n";
	print "tagname  : $branch_name\n";
	print "time     : $curtime\n";
	print "issue    : $bugId\n";
	print "message  : $message\n";
	print "filedetails : @file_details\n"; 
	print "filepath : $checkInPath\n"; #file path 
 	for my $key ( keys %checkInFiles ) {
		print "filename : $key\n"; #file name
		print "version  : $checkInFiles{$key}\n";
   	}
}

#########################################
# add informations to uploaded file list
#########################################

sub addToUploadedFile {
        my($issueNo,$message,$userName, $checkInPath,%checkInFiles) = @_;
	my $file = $uploadXMLFile;
        stat($file);

        ### if destination file doesn't exist create a new one
        if (!(-e $file)) {
                open(FILE,">$file") || die "Can't write to $file: error $!\n";
                print FILE "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
                print FILE "<?xml-stylesheet type=\"text/xsl\" href=\"../filelist.xsl\"?>\n";
                print FILE "<FileList>\n";
                print FILE "<ReleaseInfo component=\"$branch_name\" release=\"RC\" date=\"rdate\" status=\"in progress\" />\n";
                print FILE "\t<FileInfo ReferenceId=\"$issueNo\">\n";
 		for my $key ( keys %checkInFiles ) {
                	print FILE "\t\t<File Name=\"$key\" Version=\"$checkInFiles{$key}\" Author=\"$userName\" Date=\"$curtime\"><![CDATA[$message]]></File>\n";
		}
                print FILE "\t</FileInfo>\n";
                print FILE "</FileList>\n";
                close(FILE);
        }

        #### if the file exists
        elsif ((-e $file) && (!(-z $file))) {
                open(INFILE,"$file") || die "Can't read $file: error $!\n";
		flock(INFILE, LOCK_EX);
                open(OUTFILE,">$file.bak") || die "Can't write to $file: error $!\n";
		flock(OUTFILE, LOCK_EX);
                my $refidflag = 0;
                my $isFilesAdded = 0;
                while(<INFILE>) {
			$refidflag = 1 if(/FileInfo ReferenceId="$issueNo"/);
                        #### We reached the end of file list so check
                        if (/<\/FileList>/ && !$refidflag && !$isFilesAdded) {
                                #### This refid entry wasn't found
                                print OUTFILE "\t<FileInfo ReferenceId=\"$issueNo\">\n";
 				for my $key ( keys %checkInFiles ) {
                			print OUTFILE "\t\t<File Name=\"$key\" Version=\"$checkInFiles{$key}\" Author=\"$userName\" Date=\"$curtime\"><![CDATA[$message]]></File>\n";
					delete $checkInFiles{$1};
				}
                                print OUTFILE "\t</FileInfo>\n";
                        }
			if($refidflag) {
				if (/\<File Name="(.*)" Version=/) {
					if($checkInFiles{$1}) {
                				print OUTFILE "\t\t<File Name=\"$1\" Version=\"$checkInFiles{$1}\" Author=\"$userName\" Date=\"$curtime\"><![CDATA[$message]]></File>\n";
						delete $checkInFiles{$1};
					} else {
                                        	print OUTFILE $_;
					}
				} elsif (/<\/FileInfo>/) {
                        		####   refidflag will be used to check the current ref position
                        		####   Reached end of this refid section
 					for my $key ( keys %checkInFiles ) {
                				print OUTFILE "\t\t<File Name=\"$key\" Version=\"$checkInFiles{$key}\" Author=\"$userName\" Date=\"$curtime\"><![CDATA[$message]]></File>\n";
					}
                               		print OUTFILE $_; #printing <\FileInfo>
					$refidflag = 0;
					$isFilesAdded = 1;
                        	} else {
                                      print OUTFILE $_;
				}
			} else {
                               print OUTFILE $_;
                        }
                }  ### end of while

                close INFILE;
                close OUTFILE;
                rename("$file.bak","$file");
        }
	&unlock($file, $LOCK_DIR);
}
	
sub getUploadTimeStamp() {
        my ($secs, $min, $hr, $day, $month, $year) = (localtime)[0,1,2,3,4,5];
        $month +=1;
        $year +=1900;
        $secs = "0".$secs if (length($secs) != 2);
        $min = "0".$min if(length($min) != 2);
        $hr = "0".$hr if(length($hr) != 2);
        $month = "0".$month if(length($month) != 2);
        $day = "0".$day if(length($day) != 2);
        return $year."/".$month."/".$day." ".$hr.":".$min.":".$secs;
}

