#!/usr/bin/perl

#################################   Constants  #################################
$ECHO = "/bin/echo";
$MKDIR = "/bin/mkdir";
$MKTEMP_PATH = "/usr/bin/mktemp";
$PBUDDY = "/usr/libexec/sbs_backup/PBuddy";
$SQLITE = "/usr/bin/sqlite3";
$TAR = "/usr/bin/tar";
$SBS_CONF = "/private/etc/sbs_backup";
$SBSProgressLogFile = "/private/var/log/sbs_backup/sbs_progress.log";
$tmpPath = "/private/var/jabberd/tmp";
$sqliteDbPath = "/private/var/jabberd/sqlite/jabberd2.db";
$ServiceConf = "75-iChatServer.plist";
$ServiceName = "iChatServer";
%$BigList = "";
%dbinfo = {};
@MasterFilesList;

$VERBOSE = 0;
$DEBUG = 0;
$FUNCLOG = 0;
$PROGRESS = 0;

if($ENV{DEBUG}) {$DEBUG = '1'; print "iChat Server backup DEBUG = 1\n";}
if($ENV{VERBOSE}) {$VERBOSE = '1'; print "iChat Server backup VERBOSE = 1\n";}
if($ENV{FUNCLOG} && $DEBUG) {$FUNCLOG = '1'; print "iChat Server backup FUNCLOG = 1\n";}
if($ENV{PROGRESS} && $DEBUG) {$PROGRESS = '1'; print "iChat Server backup PROGRESS = 1\n";}

if ($VERBOSE) {
	print("iChatServer_backup was called.\n");
}

ParseOptions();
if ($DEBUG) 
	{ dumpAssociativeArray(@ARGV); }

validateOptionsAndDispatch(@ARGV);
exit();

################################################################################
sub validateOptionsAndDispatch()
{
	%BigList = @_;
	my $nothing = 0;
	SWITCH: {
		if (uc($BigList{"-cmd"}) eq uc("actions")) { if($DEBUG) {print("actions\n");} Actions(); last SWITCH; }
		if (uc($BigList{"-cmd"}) eq uc("backup"))  { if($DEBUG) {print("backup\n");} Backup(); last SWITCH; }
		if (uc($BigList{"-cmd"}) eq uc("help"))    { if($DEBUG) {print("help\n");} Usage(); last SWITCH; }
		if (uc($BigList{"-cmd"}) eq uc("size"))    { if($DEBUG) {print("size\n");} Size(); last SWITCH; }
		if (uc($BigList{"-cmd"}) eq uc("version")) { if($DEBUG) {print("version\n");} Version(); last SWITCH; }
		$nothing = 1;
	}
	if($nothing == 1)
		{print("Legal options were not supplied!\n");Usage();}
}

################################################################################
sub Actions() 
{
	if ($FUNCLOG) 
		{ print("Start Actions-------------------------------------------------------+\n"); }

	if($VERBOSE) {
		print (qq(${PBUDDY} -c \"Print :BackupActions\" $SBS_CONF/$ServiceConf) . "\n");
	}
	$Version = qx(${PBUDDY} -c \"Print :BackupActions\" $SBS_CONF/$ServiceConf);
	print($Version);

	if ($FUNCLOG) 
		{ print("End   Actions-------------------------------------------------------+\n");
	}
}

################################################################################
sub Backup()
{
	my $OPT = $BigList{"-opt"};
	my $cmd = "";
	my $jabberDataTmpDir = "";

	umask(077);
	if ($FUNCLOG)
		{ print("Start Backup-------------------------------------------------------+\n"); }

    if ($OPT ne "configuration" && $OPT ne "data" && $OPT ne "all") {
        print "No valid -opt selected for backup operation.\n";
        return 1;
    }

	#Create our service named folder in the image.
	my $SBS_PATH=$BigList{"-path"};
	if ($SBS_PATH eq "") {
		print "No -path given. Aborting.\n";
		return 1;
	}
		
	if(! -e $SBS_PATH) {
		if ($DEBUG) { print("${MKDIR} $SBS_PATH"); }
		qx(${MKDIR} $SBS_PATH);
	}

	## Configs ##
	if ($OPT eq "all" || $OPT eq "configuration") {
		if ($PROGRESS) {
			$pString = sprintf("\"## PROGRESS :: :: iChat Server :: Backing up configuration files :: %%%f \"", 0);
			qx($ECHO $pString >> $SBSProgressLogFile);
		}

		# backup configs
#		my $configTarPath = $SBS_PATH."/".&timestamp.".iChatServer.conf.tar.gz";
		my $configTarPath = $SBS_PATH."/"."iChatServer.conf.tar.gz";
		my @configurationFiles;
		my @configurationFilesPbuddy = qx(${PBUDDY} -c \"Print :ConfigurationFilesToTar:\" $SBS_CONF/$ServiceConf);
        if ($#configurationFilesPbuddy > 1) {
            for (my $i = 1; $i < $#configurationFilesPbuddy; $i++) {
                my $configTmp = $configurationFilesPbuddy[$i];
                chomp($configTmp);
                $configTmp =~ s/^\s*//;
                push(@configurationFiles, $configTmp);
            }
        }

		if ($VERBOSE) {
			$cmd = "$TAR --ignore-failed-read -cvzf \"$configTarPath\"";
		} else {
			$cmd = "$TAR --ignore-failed-read -czf \"$configTarPath\"";
		}
		foreach $confFile (@configurationFiles) {
			# Not quoting confFile- allow for wildcard expansion since there may be any number of sm.xml files
			$cmd .= " $confFile";
		}
		if ($VERBOSE) {
			print "Executing command: $cmd\n";
		}	
		system($cmd);

		if ($PROGRESS) {
			$pString = sprintf("\"## PROGRESS :: :: iChat Server :: Backing up files :: %%%f \"", 100);
			qx($ECHO $pString >> $SBSProgressLogFile);
		}
		if ($VERBOSE) {
			print "Backed up configuration files to $configTarPath\n";
		}
#		push(@MasterFilesList, $configTarPath);iChatServer.conf.tar.gz
		push(@MasterFilesList, "iChatServer.conf.tar.gz");
	}
	
	## Data ##
	if ($OPT eq "all" || $OPT eq "data") {
		if ($PROGRESS) {
			$pString = sprintf("\"## PROGRESS :: :: iChat Server :: Backing up data files :: %%%f \"", 0);
			qx($ECHO $pString >> $SBSProgressLogFile);
		}

		# backup database
#		my $dataTarPath = $SBS_PATH."/".&timestamp.".iChatServer.data.tar.gz";
		my $dataTarPath = $SBS_PATH."/"."iChatServer.data.tar.gz";
		my $sqlFilePath = "iChatServer_data_backup.sql";
		# clear out tmp dir
		$cmd = "rm -Rf \"$tmpPath/*\"";
		system($cmd);
		for (my $i = 0; $i < 5; $i++) {
			$cmd = "$MKTEMP_PATH -d $tmpPath/jabber_backup.XXXXXXXXXXXXXXXXXXXXXXXX";
			$jabberDataTmpDir = `$cmd`;
			chomp($jabberDataTmpDir);
			if (-e $jabberDataTmpDir) {
				last;
			}
			if ($i == 4) {
				die "Error: Cannot create temporary file:\n$jabberDataTmpDir";
			}
		}

		qx(echo ".dump" | $SQLITE $sqliteDbPath > \"$jabberDataTmpDir/$sqlFilePath\");

		my $origCWD = $ENV{PWD};
		chdir("$jabberDataTmpDir");
		if ($VERBOSE) {
			$cmd = "$TAR -cvzf \"$dataTarPath\" \"$sqlFilePath\"";
			print "Executing command: $cmd\n";
		} else {
			$cmd = "$TAR -czf \"$dataTarPath\" \"$sqlFilePath\"";
		}
		system($cmd);
		chdir($origCWD);
	   	unlink("$jabberDataTmpDir/$sqlFilePath");
        qx(rm -Rf $jabberDataTmpDir);

		if ($PROGRESS) {
			$pString = sprintf("\"## PROGRESS :: :: iChat Server :: Backing up data files :: %%%f \"", 100);
			qx($ECHO $pString >> $SBSProgressLogFile);
		}
		if ($VERBOSE) {
			print "Backed up database to $dataTarPath\n";
		}
#		push(@MasterFilesList, $dataTarPath);
		push(@MasterFilesList, "iChatServer.data.tar.gz");
	}

	CreateBrowsePlist();

	if ($FUNCLOG) 
		{ print("End  Backup-------------------------------------------------------+\n"); }
}

################################################################################
sub CreateBrowsePlist()
{
	my $SBS_PATH=$BigList{"-path"};
	my $browseFilePath=$SBS_PATH . "/$ServiceName.browse.plist";

	open(OUT, ">$browseFilePath") or die ("Couldn't open the $browseFilePath file for writing.\n");
	select(OUT);

#Header
	print ('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
	print ('<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' . "\n");
	print ('<plist version="1.0">' . "\n");
	print ('    <array>' . "\n");

	for($i=0; $i<=$#MasterFilesList; $i++) {
		$LG=$MasterFilesList[$i];
		chomp($LG);
		print '        <string>'.$LG.'</string>'. "\n";
	}

#Footer
	print ('    </array>' . "\n");
    print ("</plist>" . "\n");

	close(OUT);
	select(STDOUT);  #If you don't do this you will never see output!!!
}

################################################################################
sub Size()
{
	my $OPT = $BigList{"-opt"};
	my $jabberDataTmpDir = "";

	if ($OPT ne "configuration" && $OPT ne "data" && $OPT ne "all") {
		print "No valid -opt selected for size operation.\n";
		&Usage;
	}

	umask(077);
	if ($FUNCLOG) { 
		print("Start Size-------------------------------------------------------+\n"); 
	}

	$totalsize = 0; #bytes
	if ($OPT eq "all" || $OPT eq "configuration") {
		my @configurationFiles;
		my @configurationFilesPbuddy = qx(${PBUDDY} -c \"Print :ConfigurationFilesToTar:\" $SBS_CONF/$ServiceConf);
		if ($#configurationFilesPbuddy > 1) {
			for (my $i = 1; $i < $#configurationFilesPbuddy; $i++) {
				my $configTmp = $configurationFilesPbuddy[$i];
				chomp($configTmp);
				$configTmp =~ s/^\s*//;
				push(@configurationFiles, $configTmp);	
			}
		}
		foreach my $configFile (@configurationFiles) {
			my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($configFile);
			$totalsize += $size;
		}
	}	

	if ($OPT eq "all" || $OPT eq "data") {
        # clear out tmp dir
        $cmd = "rm -Rf \"$tmpPath/*\"";
		system($cmd);
		for (my $i = 0; $i < 5; $i++) {
			$jabberDataTmpDir = `$MKTEMP_PATH -d $tmpPath/jabber_backup.XXXXXXXXXXXXXXXXXXXXXXXX`;
			chomp($jabberDataTmpDir);
			if (-e $jabberDataTmpDir) {
				last;
			}
			if ($i == 4) {
				die "Error: Cannot create temporary file:\n$jabberDataTmpDir";
			}
		}
		qx(echo ".dump" | $SQLITE $sqliteDbPath > \"$jabberDataTmpDir/$sqlFilePath\");

		my $dataTarPath = "$jabberDataTmpDir/iChatServer_data_backup_tmp.tar.gz";
		if ($VERBOSE) {
			$cmd = "$TAR -cvzf \"$dataTarPath\" \"$jabberDataTmpDir/$sqlFilePath\"";
			print "Executing command: $cmd\n";
		} else {
			$cmd = "$TAR -czf \"$dataTarPath\" \"$jabberDataTmpDir/$sqlFilePath\"";
		}
		system($cmd);
		my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($dataTarPath);
		unlink($dataTarPath);
		unlink("$jabberDataTmpDir/$sqlFilePath");
		qx(rm -Rf $jabberDataTmpDir);
		$totalsize += $size;
	}

	$totalsize /= 1024; #make kbytes
	
	print "total := ".int($totalsize)."\n";

	if ($FUNCLOG){
		print("End   Size-------------------------------------------------------+\n"); 
	}
}

################################################################################
sub Version() 
{
	if ($FUNCLOG) 
		{ print("Start Version-------------------------------------------------------+\n"); }

	if($VERBOSE) {
		print (qq(${PBUDDY} -c \"Print :Version\" $SBS_CONF/$ServiceConf) . "\n");
	}
	$Version = qx(${PBUDDY} -c \"Print :Version\" $SBS_CONF/$ServiceConf);
	print($Version);

	if ($FUNCLOG) 
		{ print("End   Version-------------------------------------------------------+\n");
	}
}

################################################################################
# ParseOptions takes a list of possible options and a boolean indicating
# whether the option has a value following, and sets up an associative array
# %opt of the values of the options given on the command line. It removes all
# the arguments it uses from @ARGV and returns them in @optArgs.
#
sub ParseOptions {
	local (@optval) = @_;
	local ($opt, @opts, %valFollows, @newargs);

	while (@optval) {
		$opt = shift(@optval);
		push(@opts,$opt);
		$valFollows{$opt} = shift(@optval);
	}

	@optArgs = ();
	%opt = ();

	arg: while (defined($arg = shift(@ARGV))) {
		foreach $opt (@opts) {
			if ($arg eq $opt) {
				push(@optArgs, $arg);
				if ($valFollows{$opt}) {
					$opt{$opt} = shift(@ARGV);
					push(@optArgs, $opt{$opt});
				} else {
					$opt{$opt} = 1;
				}
				next arg;
			}
		}
		push(@newargs,$arg);
	}
	@ARGV = @newargs;
}

################################################################################
sub dumpAssociativeArray()
{
	%BigList = @_;
	while(($theKey, $theVal) = each (%BigList))
		{ print "$theKey is the key for value $theVal\n"; }
	if($BigList{"-cmd"} eq "backup")
		{ print "cmd := ", $BigList{"-cmd"}, "\n"; }
}

################################################################################
sub timestamp()
{
	( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
	localtime(time);
	$year += 1900;
	$mon  += 1;
	if ( $hour =~ /^\d$/ ) { $hour = "0" . $hour; }
	if ( $min  =~ /^\d$/ ) { $min  = "0" . $min; }
	if ( $sec  =~ /^\d$/ ) { $sec  = "0" . $sec; }

	#my $ret = $year."-".$mon."-".$mday."-$hour:$min:$sec";
	my $ret = $year."-".$mon."-".$mday;
	return $ret;
}

################################################################################
sub Usage()
{
	print "Usage:\n";
	print "iChatServer_backup supports the following options:\n";
	#print " -cmd backup -path path -log logPath \n";
	print " -cmd backup -path path -opt option\n";
	print "    where path is the path to the mounted image where the data was backed-up.\n";
	print "    where option is one of: configuration, data, all\n";
	#print "    where logPath is the path to the backup log file for this service, it can be found in property list file := $SBS_CONF$ServiceConf\n";
	print " -cmd size -opt option :       Calculate size of the storage requirements for iChatServer.\n";
	print "    where option is one of: configuration, data, all\n";
	print " -cmd help :                   Displays this usage.\n";
	print " -cmd version :                Prints out the version value from the property list := $SBS_CONF$ServiceConf\n";
	exit(0);
}

