#!/usr/bin/perl
# bup
# by Dennis Williamson - 2012-05-04
# HostGator.com - for internal use only

use strict;
use warnings;

use LWP::UserAgent;
use Sys::Hostname;
use Pod::Usage;
use YAML qw(LoadFile);

$\ = "\n";

my $hostname = hostname;
my $hgbackupdir;

#use version; our $VERSION = qv('3.0');

sub warn_dr {
    if (-f "/opt/eig_linux/etc/.onlydr") {
        my $config; eval { $config = LoadFile("/opt/eig_linux/etc/disaster_recovery.yaml") };
        print "[!] This server performs disaster recovery backups.";
        print "[!] The NAS may only have oversized accounts from this server.";
        print "[!] For other accounts, check $config->{tohost} ($config->{ip})" if defined $config;
    }
}

sub get_user {
    # We parse args manually since we only take a single positional parameter
    my $user = shift;

    if ( $user =~ m{\w+[.][a-zA-Z.]+}xsm ) {
        $user = get_user_from_domain($user);
    }

    return $user;

}

sub get_user_from_domain {
    my $domain = shift;
    my ($curdomain, $curuser, $user);

    open(my $fh, '<', '/etc/userdomains') or die "[X] Failed to open user domains file: $!\n";
    while (<$fh>) {
        ($curdomain, $curuser) = split(/:\s+/xsm, $_);
        if ($curdomain eq $domain) {
            $user = $curuser;
            last;
        }
    }

    close($fh) or warn "[!] Failed to close user domains file: $!\n";

    if (!$user) {
        print '[X] Failed to find user for domain ' . $domain;
        exit 1;
    }

    return $user;
}

sub get_nas_assignment {
    my $url = shift;
    my $HTTP_STATUS_OK = 200;
    my $ua = LWP::UserAgent->new;
    my $response = $ua->get($url);

    if ( $response->{'_rc'} != $HTTP_STATUS_OK ) {
        print "[X] ERROR: unable to retrieve NAS assignment from $url";
        exit 1;
    } else {
        return $response->{'_content'};
    }
}

sub get_nas {
    my $url = 'http://nas.hostgator.com/assign.php?fullquery=' . $hostname;
    my $content = get_nas_assignment($url);
    my ($nas, $drive, $nas_name) = split(/\n/xsm, $content);

    return ($nas, $drive, $nas_name);
}

sub read_vps_config {
    my $ctid = shift;
    my $vzconfig = "/etc/vz/conf/${ctid}.conf";
    my ($veid, $ve_private);

    sub return_default {
        my $ctid = shift;
        warn "[!] Warning: unable to open vzconfig for $ctid\n";
        return '';
    }

    open(my $fh, '<', $vzconfig) or return return_default($ctid);

    while ( my $line = <$fh> ) {
        if ( $line =~ m{^VE_PRIVATE="?([^"]+)"?} ) {
            $ve_private = $1;
        } elsif ( $line =~ m{^VEID="?([^"]+)"?} ) {
            $veid = $1;
        }
    }
    close($fh);

    if ( $ve_private =~ m{^(/vz[^/]*/private/)\$VEID} ) {
        $ve_private = $1 . $veid;
    }

    return $ve_private . '/fs/root';

}

sub bup {
    my ($nas, $drive, $user_dir) = @_;
    $user_dir ||= '';
    my $dest_dir = "$drive/$hostname$user_dir";
    my $command = '/usr/bin/ssh';
    my @args = ('-t', '-i',
                "$hgbackupdir/backupkey",
                '-o', 'PasswordAuthentication=no',
                '-o', 'StrictHostKeyChecking=no',
                "root\@$nas",
                "dest_dir=$dest_dir; ruser=$ENV{'RUSER'}; " . q{printf '%s: ' 'NAS';
                   uname -n;
                   while :;
                   do
                     if [[ -d $dest_dir ]];
                     then
                       break;
                     fi;
                     printf '%s' "[!] Directory $dest_dir doesn't exist";
                     dest_dir=${dest_dir%/*};
                     printf '%s\n' ", trying ${dest_dir:-/}";
                     if [[ -z $dest_dir ]];
                     then
                       dest_dir=/;
                       break;
                     fi;
                   done;
                   cd "$dest_dir";
                   printf '%s: ' 'Current directory';
                   pwd;
                   RUSER=$ruser CWD=$dest_dir bash
                 }
        );

    warn_dr();
    exec $command, @args or die "[X] ssh to $nas failed: $!\n";
}

sub main {
    my ($user, $user_dir);

    if ($#ARGV > 0) { # only use 1 argument
        warn "[!] Warning: extra arguments ignored\n";
    }
    if ($ARGV[0]) {
        if (grep {$_ eq $ARGV[0]} qw{--help -h -? --man --doc}) {$\ = ''; pod2usage(-verbose => 99);}
        chomp($user = $ARGV[0]);
        if ($hostname =~ m{^vps}) {
            $user_dir = read_vps_config($user);
        } else {
            chomp($user = get_user($ARGV[0]));
            $user_dir = (getpwnam($user))[7] or warn "[!] Warning: user not found\n";
        }
    }

    if (-d '/admin/hgbackupdir') {
        $hgbackupdir = '/admin/hgbackupdir';
    } else {
        $hgbackupdir = '/home/hgbackupdir';
    }

    if (qx(/sbin/chkconfig --list datacycle 2>/dev/null) =~ /:on/) {
        print "[!] Unable to check backups. Server is configured to use datacycle.\n";
        exit;
    }

    my ($nas, $drive, $nas_name) = get_nas();

    if ($nas && $drive) {
        print "Backup server for $hostname is $nas_name ($nas) on $drive";
        bup($nas, $drive, $user_dir);
    } else {
        print '[X] ERROR: Unable to retrieve NAS information';
        exit 1;
    }
}

main();

__END__

=head1 NAME

 bup - Log in to the NAS box assigned to the server and go to the directory 
       containing the backup data

=head1 DESCRIPTION

 This script will log in to the NAS box assigned to the server. The current 
 directory will be set to the one that contains the backup data for the 
 server. Optionally, it will cd into the directory on the NAS for a user 
 if the username or domain name is supplied as an argument. For VPSs, a 
 container number may be supplied as an argument and it will cd into the 
 fs/root directory of that container on the NAS.

=head1 SYNOPSIS

 bup [username|domain]
 bup [container]

=head1 OPTIONS

 -?, --help          Show this message

=cut

