#!/usr/bin/env perl

use strict;

die "Not configured for SSH/NFS, exiting\n" if ( !-f "/opt/eig_linux/etc/backup_server_info.conf" );

my $hostname = `hostname`;
chomp $hostname;
my %mounts;
foreach my $line ( `cat /proc/mounts | grep backup | grep -v fake | awk '{print \$1" "\$2}'` ) {
        $mounts{nfs}{$2} = $1 if ( $line =~ m/^(\d+\.\d+\.\d+\.\d+\:\/backup\d+)\s+(\/backup\d+)$/ );
        $mounts{iscsi}{$2} = $1 if ( $line =~ m/^(\/dev\/sd\w+)\s+(\/backup\d+)$/ );
}
my $cmd;
my $errors;

# Unmount duplicate backups
foreach my $mount ( keys %{ $mounts{iscsi} } ) {
        print "Testing $mount\n";
        if ( $mounts{nfs}{$mount} ) {
                print "Fixing $hostname:$mount: $mounts{iscsi}{$mount}\n";
                $cmd = "killfake -a && umount $mounts{nfs}{$mount} && umount $mounts{iscsi}{$mount}";
                print "$cmd\n";
                system("$cmd"); # == 0 or print `hostname` . " Failed: $!\n";
        } else {
                print "Failed to find NFS mount for $mount" . `hostname` . "\n";
		$errors .= "Failed to find NFS mount for $mount" . `hostname` . "\n";
        }
}
%mounts = ();
foreach my $line ( `cat /proc/mounts | grep backup | grep -v fake | awk '{print \$1" "\$2}'` ) {
        if ( $line =~ m/^(\/dev\/sd\w+)\s+(\/backup\d+)$/ ) {
        	$mounts{iscsi}{$2} = $1;
		$errors .= "iSCSI mount still found: $mounts{iscsi}{$2}\n";
	}
}
if ( $errors ) {
	print "Errors detected, exiting:\n$errors\n";
	die "Not going to continue\n";
}

# Logout all iSCSI sessions
system('iscsiadm -m session 2&>1 > /dev/null  && (iscsiadm -m node --logoutall=automatic && ls /var/lib/iscsi/nodes | grep iqn |grep backup | sed -e "s/\///g" | xargs -i iscsiadm -m node -o delete -T {}) || ( ls /var/lib/iscsi/nodes | grep iqn |grep backup | sed -e "s/\///g" | xargs -i iscsiadm -m node -o delete -T {})') == 0 or die "Failed to clear iSCSI sessions: $@\n";

# Mount all again
system("mount -a") == 0 or die "Failed to mount all: $!\n";
