#!/usr/bin/perl
use strict;
use Data::Dumper;
use YAML qw( LoadFile );

my $config_dir = "/opt/eig_linux/conf";
my $bin_dir = "/opt/eig_linux/bin";
my $config_file = "partitions.yaml";
my $run = 1 if ( $ARGV[0] eq 'run' );

my $server_conf = "/opt/eig_linux/conf/backup_server.conf";
my $conf =  LoadFile($server_conf) or die "Unable to load $server_conf";
die "backup_server.conf does not have type zfs!" unless $conf->{"type"} eq "zfs";

my $data = LoadFile("$config_dir/$config_file") if ( -f "$config_dir/$config_file");
my $backup_mountparent = "/home";
my $zfs_basepool = "backups";
my $RATIO = "1.05";
my $RESERVE = ".0";
my $FUDGE = ".91";

my %zfs_lv;
my @zfslvdump = `zfs list -H -oname,mountpoint`;
foreach my $zfsline (@zfslvdump) {
  my @part = split(/\t/, $zfsline);
  my $temp = $part[1];
  chomp $temp;
  $zfs_lv{$part[0]} = $temp;
}

# Iterate our backup config
foreach my $entry ( sort { $data->{$a}{plabel} cmp $data->{$b}{plabel} } keys %$data ){
  next if ( !defined($data->{$entry}{plabel}) || defined($zfs_lv{$zfs_basepool."/".$data->{$entry}{plabel}}) );
  my $lastmount = $data->{$entry}{'cmount'};
  $lastmount =~ s/^\///;
  my $mountpoint = $backup_mountparent."/".$data->{$entry}{'chostname'}."/".$lastmount;
  my $quota = sprintf("%.0f",(($data->{$entry}{'homesize'} * $RATIO * $FUDGE) * 1024));
  my $cmd = "zfs create -o mountpoint=\"$mountpoint\" -o quota=".$quota."G \"$zfs_basepool/".$data->{$entry}{'plabel'}."\"";
  print "Creating ZFS Slice: $cmd\n";
  if ( $run ) {
    system("$cmd") == 0 || die "Failed: $!\n";
  }
}

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