#!/usr/bin/perl

use String::CRC32;
use strict;

my $ROOT_PATH=$ARGV[0];
my $RESULT_FILE=$ARGV[1];

#print $ARGV[0];

#-------------------------------------------------------------------
# recursively read directory tree
# ------------------------------------------------------------------

my ($dir) = $ROOT_PATH;
my($filelist) = [];
my $resultXML = [];

sub recursedir($$) {

	my($dir)  = shift @_;
	my($list) = shift @_;

	#-----------------------------------------------------------
	#   get files, skipping hidden . and ..
	#-----------------------------------------------------------
	
	if( opendir( DIR, "$dir" ) ) {

		for my $file( grep { !/^\./ } readdir DIR ) {

			if( -d "$dir/$file" ) {

				recursedir("$dir/$file", $list);
				
			} elsif( -f "$dir/$file" ) {

				#-----------------------------------
				# caclulate CRC32 
				# ----------------------------------
				 
				my $crc = myMkCRC32( "$dir/$file" );
				$crc = sprintf("%X", $crc);

				#-----------------------------------
				# remove ROOT_PATH from file path
				# ----------------------------------
				
			        my $path = "$dir/$file";
				$path =~ s/$ROOT_PATH\///g;

				#-----------------------------------
				# make XML
				# ----------------------------------
				
				my $length = -s "$dir/$file";
			        my $xml_text;	

				$xml_text = "\t<file crc32=\"$crc\" length=\"$length\">$path</file>";
				push @$resultXML, $xml_text;								
			}
		}
		
		closedir DIR;		
	} else {

		die "Error opening $ROOT_PATH!";
	}			
}

#-------------------------------------------------------------------
# Make index.xml
# ------------------------------------------------------------------


sub myMakeIndexXML {

	#-----------------------------------------------------------
	# make XML head
	# ----------------------------------------------------------
	
	my $timestamp = sprintf("%02d:%02d %02d.%02d.%04d", (localtime)[2,1], (localtime)[3], (localtime)[4]+1, (localtime)[5]+1900);
	
	push @$resultXML, "<update lastchange=\"$timestamp\">";

	push @$resultXML, "<default-profile>";
	
	recursedir $dir, $filelist;
	
	push @$resultXML, "</default-profile>";
	
	push @$resultXML, "</update>";
}

#------------------------------------------------------------------
# caclulate CRC32 of the requested file
# -----------------------------------------------------------------

sub myMkCRC32 {

	open(SOMEFILE, "@_");
	my $res = crc32(*SOMEFILE);
	close(SOMEFILE);

	return $res;
}

#------------------------------------------------------------------
# compile results
# -----------------------------------------------------------------

myMakeIndexXML;

open OUT1, ">$RESULT_FILE" or die "Cannot open file: $!\n";
print OUT1 $_, "\n" for(@$resultXML);
close OUT;
exit;
