#!/usr/bin/perl
#
# File:  "$Id: do_backup.pl,v 1.4 2009/02/24 05:30:19 jonas_liu Exp $"
#
# Description:
#
# BUGS:
#
# CHANGES:
#
# NOTE:
#
# First Created on 2008/08/20 by jonas_liu@openfind.com.tw
# Last Modified on "$Date: 2009/02/24 05:30:19 $" by  $Author: jonas_liu $
#
# Copyright (c)2008 Openfind Information Technology INC.
# All rights reserved.
#
use strict;

my $CVSREV = '$Revision: 1.4 $';
my $CVSID = substr($CVSREV, 11, -2);

my ($SEC, $MIN, $HOUR, $DAY, $MON, $YEAR) = localtime(time);
my $ARCH_FILE = $ARGV[0];
my $LIST_FILE = $ARGV[1];
my $BACKUP_BASE = defined($ARGV[2]) ? $ARGV[2] : "/webmail";
my $BACKUP_DIR = "$BACKUP_BASE/backup";
my $TAR_BIN = "tar";
my $GZIP_BIN = "gzip";

sub GetBackupFilePath {
	for(my $n=0; $n<128; $n++) {
		my $s = sprintf("$BACKUP_DIR/$ARCH_FILE%s.tar.gz", ($n ? "_$n" : ""));
	
		return $s if(! -e $s);
	}
	return "";
}

sub main {
	return -1 if($#ARGV < 1);

	my $ArchFile;
	my $nFileCnt = 0;

	if(! -r $LIST_FILE) {
		print "ERROR: cannot read the file list.\n";
		return -1;
	}

	if("" eq ($ArchFile = GetBackupFilePath())) {
		print "ERROR: cannot determine backup file path.\n";
		return -1;
	}
	$ArchFile =~ s/\.gz$//;

	print "backup dir: $BACKUP_DIR\n";
	
	if(! -e $BACKUP_DIR) {
		if(!mkdir($BACKUP_DIR, 0750)) {
			print "ERROR: cannot create $BACKUP_DIR: $!\n";
			return -1;
		}
	}
	if(! -d $BACKUP_DIR) {
		print "ERROR: $BACKUP_DIR is not a directory.\n";
		return -1;
	}

	foreach my $File (split(/\n/, `cat $LIST_FILE`)) {
		next if(! -r $File || ! -r "$BACKUP_BASE/$File");

		my $szFlag = $nFileCnt ? "rf" : "cf";
		if(system("$TAR_BIN $szFlag $ArchFile $BACKUP_BASE/$File > /dev/null 2>&1")) {
			printf("ERROR: cannot backup $File: ret=%d\n", $? >> 8);
			return -1;
		}
		$nFileCnt++;
	}

	if($nFileCnt == 0) {
		print "no file need to backup.\n";
		return 0;
	}
                                                	
	if(0 != system("($GZIP_BIN -f $ArchFile) > /dev/null 2>&1")) {
		print "ERROR: cannot compress $ArchFile";
		return -1;
	}

	print "backup file: $ArchFile.gz ($nFileCnt files)\n";
	return 0;
}

exit main();
