#!/usr/bin/perl

# hits port 9279 on backup servers that box is connected to. Backup server says 'maint' or 'production'. 
use strict;
use JSON qw( decode_json );
use IO::Socket::INET;
use Proc::PID::File;
use lib '/opt/eig_linux/lib';
use BackupRestore;

if (Proc::PID::File->running()){
    print "$0 is already running!\n";
    exit();
}

my $maintfile = '/opt/eig_linux/etc/.backup_maint_enabled'; #used to keep track of whether we did the unmounting or not.
my $mode = 'none';
my $br = new BackupRestore();

$mode = getfromsocket($br->{config}->{'backup_ip'});
if($mode eq undef) {
    print "unable to connect to $br->{config}->{'backup_ip'}:9279\n";
}
print "mode for $br->{config}->{'backup_ip'} is $mode\n";

if($mode eq 'none' or $mode eq undef){
    print "unable to connect to any target to check maint mode\n";
    exit;
}

my ($mounted, $disabled) =  check_state();
if($mode eq 'maint'){
    if ( !-f $maintfile || !$disabled ) {
        print "Maint detected but not enabled, running backuphelper maint\n";
        system("/opt/eig_linux/bin/backuphelper maint") == 0 or print "Failed to enable maint: $@\n";
        system("/bin/touch $maintfile");
    } elsif ($mounted) { 
        print "mode is maint but backups mount.  Attempting to unmount...\n";
        system("/opt/eig_linux/bin/backuphelper umount") == 0 or print "Failed to mount backups: $@\n";
    } else {
        print "Already in maint mode\n";
    }
} elsif ($mode eq 'production'){
    if( -e $maintfile && ( !$mounted || $disabled ) ) {
        print "mode is production, need to 'backuphelper reset_queue'\n\n";
        system("/opt/eig_linux/bin/backuphelper reset_queue") == 0 or print "Failed to enabled backups: $@\n";
        unlink($maintfile);
    } elsif ( !-e $maintfile && !$mounted && !$disabled ) {
        print "mode is production but backups unmount.  Attempting to mount...\n";
        system("/opt/eig_linux/bin/backuphelper mount") == 0 or print "Failed to mount backups: $@\n";
    } elsif ( !-e $maintfile && !$mounted && $disabled ) {
        print "mode is production, devs unmounted or backups disabled locally. I apparently did not do the unmounting or disabling, so I am doing nothing\n";
    } else {
        print "Already in production mode\n";
    }
} else {
    print "Unknown mode: $mode\nDoing nothing\n";
}



##################### subs ####################

sub getfromsocket {
    my $host = shift;
    my $sock = new IO::Socket::INET (PeerAddr => $host, PeerPort => '9279', Proto => 'tcp', Timeout => 3) ;
    return undef unless $sock;
    chomp(my $read = <$sock>);
    close $sock;
    return $read;
}

sub check_state {
    my $m = 1;
    my $d = -f '/etc/disable_backups' ? 1 : 0;

    # Expected Mounts
    my $mount_cache = '/opt/eig_linux/data/backup_mount_cache.json';
    return $m,$d unless -f $mount_cache;
    my $expected_mounts;
    open(my $fh, "<", "$mount_cache");
    $expected_mounts  = decode_json(<$fh>);
    close $fh;

    # Active Mounts
    my $active_mounts;
    open (my $fh, '<', '/proc/mounts');
    while ( my $line = <$fh>) {
        chomp ($line);
        next unless $line =~ m%\s(/backup\d*)\s+(autofs|nfs4)%;
        $active_mounts->{$2}->{$1} = $line;
    }
    close $fh;

    foreach my $mount (keys %$expected_mounts){
        if ($br->{config}->{autofs}) { 
            $m = 0 if not defined $active_mounts->{autofs}->{$mount};
        } else {
            $m = 0 if not defined $active_mounts->{nfs4}->{$mount};
        }
    }
    return $m, $d;
}
