#!/usr/bin/perl

use strict;
use YAML qw( LoadFile );
use Data::Dumper;

my $run = 1 if ( $ARGV[0] eq 'run' );

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

my $bk = new BackupServer;

my $config_dir = "/opt/eig_linux/conf";

my $data = $bk->get_partitions();
if(keys %$data == 0){
  die "partition data didn't load.  Please run $Bin/setup_backups";
}
my $date = time();
my %iscsi_plabels = ();
my %iscsi_hosts = ();
my $todo = 0;
if ( -f "/etc/scst.conf" ) {
    foreach my $entry ( `grep DEVICE /etc/scst.conf | awk '{print \$2}'` ) {
        chomp $entry;
        $iscsi_plabels{$entry} = 1;
    }
}
if ( -f "/etc/tgt/targets.conf" ) {
    foreach my $entry ( `grep initiator-address /etc/tgt/targets.conf | awk '{print \$2}'` ) {
        chomp $entry;
        $iscsi_hosts{$entry} = 1;
    }
}

# Get list of partitions for the host
my %partitions = ();
foreach my $entry ( keys %$data ) {
    $partitions{$$data{$entry}{chostname}}{plabels}{$$data{$entry}{plabel}} = 1;
    $partitions{$$data{$entry}{chostname}}{ip} = $$data{$entry}{backnetip};
}

# Load current fstab
if ( $run ) {
    system("([ -d $config_dir/backups ] || mkdir $config_dir/backups) && cp -a /etc/fstab $config_dir/backups/fstab.$date") == 0 or die "Failed to backup current fstab: $!\n";
}
open(FSTAB, "+</etc/fstab");
my %entries;
foreach my $line (<FSTAB>) {
    $entries{$1} = 1 if ($line =~ m/^LABEL=([\w\d\.\-\_]+)\s/);
}

# Load current exports
if ( $run ) {
    system("([ -d $config_dir/backups ] || mkdir $config_dir/backups) && cp -a /etc/exports $config_dir/backups/exports.$date") == 0 or die "Failed to backup current exports $!\n";
}
open(EXPORTS, "+</etc/exports");
my %exports;
foreach my $line (<EXPORTS>) {
    $exports{$1}{ip} = $2 if ($line =~ m/^\/home\/([\w\.-]+)\s+(\d+\.\d+\.\d+\.\d+)/);
    $exports{"$1$2"}{ip} = "exists" if ($line =~ m/^\/home\/([\w\.-]+)\/backup(\d*)\s+(\d+\.\d+\.\d+\.\d+)/);
}
my $cmd;
my $partition;
foreach my $host ( keys %partitions ) {
    if ( $iscsi_hosts{$partitions{$host}{ip}} ) {
        print "Skipping iSCSI mounted host $host\n";
        next;
    }
    if ( !$exports{$host} ) {
	print "Adding base export for $host to /etc/exports\n";
        $todo = 1;
	if ( $run ) {
	    print EXPORTS "/home/$host $partitions{$host}{ip}(ro,fsid=0,no_subtree_check,sync)\n";
	} else {
	    print "/home/$host $partitions{$host}{ip}(ro,fsid=0,no_subtree_check,sync)\n";
	}
    }
    foreach my $plabel ( keys %{ $partitions{$host}{plabels} } ) {
        if ( $iscsi_plabels{$plabel} ) {
            print "Skipping iSCSI plabel $plabel\n";
            next;
        }
        if ($plabel =~ m/^[\w-]+\.(\d*)/ ){
            $partition = $1;
        } else {
            print "Plabel '$plabel' not parsing, skipping\n";
            next;
        }

        if ( !-d "/home/$host/backup$partition" ) {
            # Make mount points
	    $cmd = "mkdir -p /home/$host/backup$partition";
            $todo = 1;
	    if ( $run ) {
                system($cmd) == 0 or die "Command failed: $!\n";
            } else {
                print "Need to create /home/$host/backup$partition\n";
            }
        }

	# Add entries to fstab
	if ( !$entries{$plabel} && $bk->get_config_value('type') ne "zfs" ) {
	    print "Adding $plabel to fstab\n";
            $todo = 1;
	    if ( $run ) {
                print FSTAB "LABEL=$plabel		/home/$host/backup$partition		ext4	defaults,noatime,nodiratime	0 0\n";
            } else {
                print "LABEL=$plabel		/home/$host/backup$partition		ext4	defaults,noatime,nodiratime	0 0\n";
            }
	}

	# Add entries to exports
	if ( !$exports{"$host$partition"} ) {
            $todo = 1;
	    if ( $run ) {
	        print EXPORTS "/home/$host/backup$partition $partitions{$host}{ip}(ro,sync,no_root_squash)\n";
	    } else {
	        print "Adding /home/$host/backup$partition $partitions{$host}{ip}(ro,sync,no_root_squash) to exports\n";
            }
	}
    }
}

close(FSTAB);
close(EXPORTS);

if ( $run ) {
    # Mount partitions if needed
    if ($bk->get_config_value('type') eq "zfs") {
        system("zfs mount -a") == 0 or die "Failed to mount all partitions: $!\n";
    }else{
      system("mount -a") == 0 or die "Failed to mount all partitions: $!\n";
    }

    # Load exports
    system("exportfs -a") == 0 or die "Failed to export all: $!\n";
}

exit 2 unless ( $todo );

