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

use constant OPT => [
			"-h",			#0
			"-n",			#1
			"-s",			#2
			"-r",			#3
			"-p",			#4
			">",			#5
			"@",			#6
			".tar",			#7
		];
use constant BACKUPPC_BIN_DIR => "/usr/share/backuppc/bin/";
use constant BACKUPPC_ARCHIVE_SCRIPT => "BackupPC_tarCreate";
use constant DEFAULT_ARCHIVE_DIR => "/var/lib/backuppc/";
use constant DEFAULT_CONF_DIR => "/etc/backuppc/";
use constant DEFAULT_HOSTS_FILENAME => "hosts";

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

sub printUsage {
	print "BackupPC_tarCreateAll [--dir|-d /path/to/archive/dir] (default: /var/lib/backuppc/)\n";
	print "                      [--cfgdir|-c /path/to/config/dir] (default: /etc/backuppc/)\n";
	print "                      [--hostfile|-f hosts_filename] (default: hosts)\n";
	print "                      [--help|-h (print 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";
}

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"."-";
}

#Evaluating arguments
my $archive_dir = '';
my $cfg_dir = '';
my $hosts_file = '';
my $print_usage;
my $pretend;

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

if (!$archive_dir) {$archive_dir = DEFAULT_ARCHIVE_DIR;}
else {if ($archive_dir !~ m/\.*\/$/) {$archive_dir .= "/";}}
if (!$cfg_dir) {$cfg_dir = DEFAULT_CONF_DIR;}
else {if ($cfg_dir !~ m/\.*\/$/) {$cfg_dir .= "/";}}
if (!$hosts_file) {$hosts_file = DEFAULT_HOSTS_FILENAME;}
my $hosts_file_name = $cfg_dir.$hosts_file;

if (!$print_usage) {
	my $prefix = getPrefix;
	open H, "$hosts_file_name";
	my @hosts = ();
	my $i = 0;
	while (!eof(H)) {
		my @tokens = split(/\ |\t/, <H>);
		#Lines of hosts file beginning with 'host' (first line), 'localhost' and '#' are not considered.
		#I added 'archive' in my configuration, feel free to change
		if (!($tokens[0] =~ m/^#\.*|^host\.*|^archive\.*|^localhost\.*/ )) 
			{$hosts[$i] = $tokens[0];
			$i++;
		}
	}
	close H;
	#@share[$i][$j]: j-th share of the i-th server
	my @share = ([],[]);
	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/) {
				getShares($share[$i],$row);
				#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]}) {
					$out_files[$nf] = $archive_dir.
                                                	$prefix.
							$share[$i][$j].
                                                	OPT->[6].
                                                	$hosts[$i].
                                                	OPT->[7];
					my $cmd = BACKUPPC_BIN_DIR.
						BACKUPPC_ARCHIVE_SCRIPT.
						" ".OPT->[0]." ".
						$hosts[$i].
						" ".OPT->[1]." -1".
						" ".OPT->[2]." ".
						$share[$i][$j].
						" ".OPT->[3]." /".
						" ".OPT->[4]." /".
						" / ".
						OPT->[5]." ".
						$out_files[$nf];
					$nf++;
					if ($pretend) {
						print "Will execute $cmd\n";
					}
					else {
						open(TARCREATE,"$cmd|") || die "Failed: $!\n";
						while (<TARCREATE>) {
							#expect for error conditions?
						}
						close TARCREATE;
					}
				}
			}
		close F;
		}
	}
	foreach (@out_files) {
		if ($pretend) {
			print "Will compress $_ in $_.gz\n";
		}
		else {
			gzip $_ => "$_.gz" or die "gzip failed: $GzipError\n";
			`rm $_`;
		}
	}
}
else {printUsage;}
