#!/usr/bin/env perl

# Use mandatory external modules
use strict;
use Cwd;
use File::Basename;
use Data::Dumper;
use POSIX;
use Config;
use Getopt::Long;

# Determine installation dir name
our $SELF_DIR = dirname(dirname(Cwd::abs_path(__FILE__)));

# Include parts of the system
require $SELF_DIR . '/lib/version.pm';
require $SELF_DIR . '/lib/config.pm';
require $SELF_DIR . '/lib/log.pm';
require $SELF_DIR . '/lib/db.pm';

#-----------------------------------------------------------------
#Parse options

my $config_file = "mmm_lvm.conf";
my $host_name;
my $copy_method;
my $dest_dir;

GetOptions( "config=s"      => \$config_file,
            "host=s"        => \$host_name,
            "copy-method=s" => \$copy_method,
            "dest-dir=s"    => \$dest_dir);

#-----------------------------------------------------------------
# Read config file
our $config = ReadConfig($config_file);
$copy_method = $config->{default_copy_method} unless ($copy_method);

print "Copy method: '$copy_method'\n\n";

# Parse clone dirs
my @clone_dirs : shared = split(/\,/, $config->{clone_dirs});
$config->{clone_dirs} = \@clone_dirs;

# Check host name
my $clone_host = $config->{host}->{$host_name};
PrintUsage("Invalid host name!") unless ($clone_host);

# Check copy method
my $method = $config->{copy_method}->{$copy_method};
PrintUsage("Invalid copy method ($copy_method)!") unless ($method);

# Check copy method
my $should_be_empty = ($method->{incremental} ne 'yes');
PrintUsage("Invalid destination directory!") unless (CheckDestDir($dest_dir, $should_be_empty));

# Print info
LogNotice("Host: '$host_name'");
LogNotice("Copy method: '$copy_method'");
LogNotice("Dirs to backup: '" . join(', ', @clone_dirs) . "'");

#-----------------------------------------------------------------
# Create config shortcuts
my $this = $config->{this};
my $host = $config->{host}->{$this};

LogNotice("-----------------------------------------------------------------");
# Executing copying process
my $res = system("$SELF_DIR/sbin/mmm_get_dump --config $config_file --host $host_name --copy-method $copy_method --dest-dir $dest_dir");
if ($res) {
    LogError("Error: Can't copy data from remote server");
    exit(1);
}

LogNotice("-----------------------------------------------------------------");
LogNotice("Backup process done!\n\n\n");

exit(0);

#-----------------------------------------------------------------
sub PrintUsage($) {
    my $error = shift;
    print "ERROR: $error\n\n";
    print "Usage: $0 [--config <config file>] --host <host> --dest-dir <dir> [--copy-method <method>]\n";
    print "Where:\n";
    print "  Host = " . join('|', keys(%{$config->{host}})) . "\n";
    print "  Copy method = " . join('|', keys(%{$config->{copy_method}})) . " (default = $config->{default_copy_method})\n\n";
    exit(1);
}

#-----------------------------------------------------------------
sub CheckDestDir($$) {
    my $dir = shift;
    my $should_be_empty = shift;
    return 0 unless ($dir);

    mkdir($dir) unless (-e $dir);

    return 0 if (-f $dir);
    return 0 unless (-r $dir && -x $dir && -w $dir);
    return 0 if ($should_be_empty && scalar(glob("$dir/*")));
    return 1;
}
