#!/usr/bin/perl -w
use lib qw(/etc/default/);
use Getopt::Long;
use strict;
use warnings;
use IO::Compress::Gzip qw(gzip $GzipError);

BEGIN {
	require "BPC_tarCreateAll.conf";
}

use constant OPT => [
	"-h",	#0
	"-n",	#1
	"-s",	#2
	"-r",	#3
	"-p",	#4
	">",	#5
	"@",	#6
	".tar"	#7
];

# Extact shares
sub getShares {
	my $j = 0;
	while ($_[1] =~ m/'([^']+)'/g) {
		$_[0][$j] = $1;
		$j++;
	}
}

sub printUsage {
	print "This script reads BackupPC config files and make tar.gz archive of all SMB shares\n";
	print "Usage:\n";
	print "BackupPC_tarCreateAll <--dir|-d /path/to/archive/dir> (required)\n";
	print "                      [--cfgdir|-c /path/to/config/dir] (default: ".Conf::DFL_CNF_DIR.")\n";
	print "                      [--hostfile|-f hosts_filename] (default: ".Conf::DFL_HST_FLN.")\n";
	print "                      [--user|-u backuppc_user] (default: ".Conf::BPC_USER.")\n";
	print "                      [--help|-h (prints this help)]\n";
	print "                      [--pretend|-p] (do nothing, only shows what would be done)\n";
	print "\n";
	print "Archive files will be created as <share name>@<host name>.tar.gz under archive directory\n";
}

# Returns YYYYMMDD prefix
sub getPrefix {
        my @timeData = localtime(time);
        my $year = $timeData[5]+1900;
        my $mounth = sprintf("%02d", $timeData[4]+1);
	my $day = sprintf("%02d", $timeData[3]);
        return "$year"."$mounth"."$day";
}

sub sendMail {
	# Mail delivery by local MTA
	open(MAIL, "|/usr/sbin/sendmail -t");
	print MAIL "To: ".Conf::EMAIL_ADDRESS."\n";
	print MAIL "Subject: ".Conf::EMAIL_SUBJECT."\n";
	print MAIL "$_[0]\n";
	close(MAIL);
}

# Arguments
my $archive_dir = '';
my $cfg_dir = '';
my $hosts_file = '';
my $print_usage;
my $pretend;
my $user = '';

GetOptions(
	"dir|d=s" => \$archive_dir,
	"cfgdir|c=s" => \$cfg_dir,
	"hostsfile|f=s" => \$hosts_file,
	"user|u=s" => \$user,
	"help|h" => \$print_usage,
	"pretend|p" => \$pretend
	);

my $output = '';

if (!$print_usage) {
	# Checks if current user is backuppc or other user provided by command line
	my $current_user = getpwuid($<);
        if (!$user) {
		$user = Conf::BPC_USER;
	}
	if ($current_user ne $user) {
		print "\nWARNING: you are logged in as $current_user. Login as ".$user." to run this script.\n\n";
		printUsage;
		die ("Exiting...\n");
	}

	# Checks if archive directory has been provided by command line
	if (!$archive_dir) {
		print "\nWARNING: You must specify an archive path with -d or --dir option!\n\n";
		printUsage;
	        die ("Exiting...\n");
	}
	else {if ($archive_dir !~ m/\.*\/$/) {$archive_dir .= "/";}}
	
	# Checks if config dir has been provided by command line. Otherwise sets to default
	if (!$cfg_dir) {
		$cfg_dir = Conf::DFL_CNF_DIR;
	} else {
		if ($cfg_dir !~ m/\.*\/$/) {
			$cfg_dir .= "/";
		}
	}

	# Checks if hosts file name has been provided by command line. Otherwise sets to default
	if (!$hosts_file) {
		$hosts_file = Conf::DFL_HST_FLN;
	}
	my $hosts_file_name = $cfg_dir.$hosts_file;

	# Append current timestamp (YYYYMMDD) to archive path
	$archive_dir .= getPrefix."/";
	if ($pretend) {
		$output .= "- Archive files will be stored in directory ".$archive_dir."\n";
	} else {
		unless (mkdir $archive_dir) {
			die ("Unable to create directory $archive_dir\n");
		}
		$output .= "- Directory $archive_dir created.\n";
	}
	
	open H, "$hosts_file_name";

	# Hosts array.
	my @hosts = ();
	my $i = 0;
	
	while (!eof(H)) {
		my @tokens = split(/\ |\t/, <H>);
		# Considers only first word. Excludes header line, comments and empty lines.
		# TODO: give the user the ability to specify its own exclusion list, keeping here # and "host"
		if (!($tokens[0] =~ m/^#\.*|^\bhost\b|^archive\.*|^$/)) {
			$hosts[$i] = $tokens[0];
			$i++;
		}
	}
	close H;
	
	# Shares array.
	# @share[$i][$j] is j-th share of the i-th server
	my @share = ([],[]);
	# Archive file names array
	my @out_files = ();
	my $nf = 0;
	for ($i = 0; $i <= $#hosts; $i++) {
		open F, "<".$cfg_dir.$hosts[$i].".pl";
		while (!eof(F)) {
			my $row = <F>;
			if ($row =~ m/SmbShareName|TarShareName/) {
				getShares($share[$i],$row);
				# Builds command 
				#/usr/share/backuppc/bin/BackupPC_tarCreate -h <host> -n -1 -s '<share>' -r / -p / / > <path_to_tar_file>
				for my $j (0..$#{$share[$i]}) {
					my $shareij = $share[$i][$j];
					$shareij =~ s/\///g;
					$out_files[$nf] = $archive_dir.
							$shareij.
                                                	OPT->[6].
                                                	$hosts[$i].
                                                	OPT->[7];
					$out_files[$nf] =~ s/\s/_/g;
					my $cmd = Conf::BPC_BIN_DIR.
						Conf::BPC_ARC_SCR.
						" ".OPT->[0]." ".
						$hosts[$i].
						" ".OPT->[1]." -1".
						" ".OPT->[2]." ".
						"\'".$share[$i][$j]."\'".
						" ".OPT->[3]." /".
						" ".OPT->[4]." /".
						" / ".
						OPT->[5]." ".
						$out_files[$nf];
						$nf++;
					if ($pretend) {
						$output .= "- Will execute $cmd\n";
					} else {
						open(TARCREATE,"$cmd|") || die "Failed: $!\n";
						while (<TARCREATE>) {
							# TODO: Expect for error conditions to handle?
						}
						close TARCREATE;
						$output .= "- Executed: $cmd\n";
					}
				}
			}
		}
	close F;
	}
	# Gzips tar file, then delete tar archive.
	foreach (@out_files) {
		if ($pretend) {
			$output .= "- Will compress $_ in $_.gz\n";
		} else {
			
			gzip $_ => "$_.gz" or die "gzip failed: $GzipError\n";
			`rm $_`;
			$output .= "- Archive $_.gz created\n";
		}
	}
	if ($pretend) {
		print $output;
	} else {
		# Send mail when finished
		sendMail($output);
	}
} else {
	printUsage;
}
