#!/usr/bin/perl

use strict;
use Sys::Hostname;
use YAML qw( LoadFile );

use FindBin qw($Bin);
use lib "$Bin/../lib";
use lib "/opt/eig_linux/lib";
use BackupServer;

my $bk = new BackupServer;
my $is_systemd = -e "/bin/systemctl";
my $hostname = hostname;
my $sshd_config = "/etc/ssh/sshd_config";
my $auth_file = "/root/.ssh/authorized_keys2";

open(SSHD_CONFIG, "+<$sshd_config");
my $update = 0;
my @out;
foreach my $line (<SSHD_CONFIG>) {
    if ( $line =~ m/^(AuthorizedKeysFile|AuthorizedKeysCommandUser|AuthorizedKeysCommand)/) {
        print "Commenting Out $1 in sshd_config\n";
        $update = 1;
        push @out, "# BACKUP # ".$line;
    } else {
        push @out, $line;
    }
}

if ($update) {
    seek(SSHD_CONFIG, 0, 0,);
    print SSHD_CONFIG @out;
    truncate(SSHD_CONFIG, tell SSHD_CONFIG);
    if ( $is_systemd ){
        print "restarting sshd via systemctl\n";
        system("systemctl restart sshd") == 0 or die "Failed to restart SSHD: $!\n";
    } else {
        print "restarting sshd via service\n";
        system("service sshd restart") == 0 or die "Failed to restart SSHD: $!\n";
    }
}
close SSHD_CONFIG;

my %out;
open(BASE, "<$auth_file");
foreach my $line ( <BASE> ) {
    ($out{hosts}{$4}{'ip'},$out{hosts}{$4}{'key'}) = ($1,"$3 root\@$4") if ( $line =~ m/^from="(\d+\.\d+\.\d+\.\d+)",([\w\d\.\,\-]+)\s+([\w\-]+\s+.*)\s+root\@([\w\d\.\-]+)/ );
}
close(BASE);

$update = 0;
my $current_config = $bk->get_partitions();
foreach my $entry ( keys %{ $current_config } ) {
    if ( !$out{hosts}{$$current_config{$entry}{chostname}} ) {
        print "$$current_config{$entry}{chostname} missing\n";
        $update = 1;
    }
    if ( $out{hosts}{$$current_config{$entry}{chostname}}{'ip'} ne $$current_config{$entry}{'backnetip'} ) {
        print "$$current_config{$entry}{chostname} IP doesn't match from backupmaster\n";
        $update = 1;
    }
    if ( $out{hosts}{$$current_config{$entry}{chostname}}{'key'} ne $$current_config{$entry}{'pubkey'} ) {
        print "$$current_config{$entry}{chostname} key doesn't match from backupmaster\n";
        $update = 1;
    }
}

exit unless ( $update );

print "Writing new $auth_file...\n";
system("chattr -iA $auth_file");
open(KEYS, ">$auth_file");
my $host;
my %added = ();
foreach my $entry ( keys %{ $current_config } ) {
    $host = $$current_config{$entry}{chostname};
    next if ( $added{$host} );
    print KEYS "from=\"$$current_config{$entry}{'backnetip'}\",no-X11-forwarding,no-port-forwarding $$current_config{$entry}{'pubkey'}\n"; 
    $added{$host} = 1;
}
close(KEYS);
system("chattr +iA $auth_file");
print "Done.\n";

1;
