#!/s/std/bin/perl

# $Id: afsalloc.pl,v 1.1.1.1 2011/01/24 22:21:38 koczan Exp $

# afsalloc.pl updates the afsalloc table with "user" afs servers

use strict;
use warnings;

use DBI;
use CSL::Pg;
use CSL::DBs;

my $dbh = DBI->connect($CSL::DBs::csdb)
  or die "Could not connect to CSDB: $!";
$dbh->do("set search_path to csdb");

# If they gave a file, redirect STDOUT to there.
my $outfile = shift @ARGV;
if ($outfile) {
  open STDOUT, '>', $outfile
    or die "$0: Could not open $outfile for writing: $!";
}

open AFSDF, "-|", "/s/std/bin/afsdf", "-R"
  or die "Could not execute afsdf: $!";

# out with the old
$dbh->begin_work;
print "Deleting old servers from afsalloc...\n";
$dbh->do("delete from afsalloc where volumetype = 'cs'");

# in with the new
my $SIZE = 4000000;
my $USED = 0;

my $partition_insert = $dbh->prepare("insert into afsalloc (afs_server, afs_part, size, used, volumetype) values (?, ?, ?, ?, ?)");
while (my $line = <AFSDF>) {
  chomp $line;
  my ($server, $part, $type) = (split /\s+/, $line)[0,1,4];

  $server .= ".cs.wisc.edu";
  $part = substr($part, 6, 1);

  my $volumetype = undef;
  if ($type eq "user") {
    $volumetype = "cs";
  } else { 
    # don't add this one
    next;
  }

  print "Adding $server $part to afsalloc as type \"$volumetype\"\n";
  $partition_insert->execute($server, $part, $SIZE, $USED, $volumetype);
}

close AFSDF;

# sanity check 
my $server_query = $dbh->prepare("select count(*) from afsalloc where volumetype = ?");
$server_query->execute("cs");
my $cs_count = $server_query->fetchrow_hashref->{count};

if ($cs_count < 1) {
  print STDERR "ERROR: 0 afs servers in afsalloc. Transaction rolled back.\n";
  print "ERROR: 0 afs servers in afsalloc. Transaction rolled back.\n";
  $dbh->rollback;
} else {
  print "All is well, committing changes to afsalloc table.\n";
  $dbh->commit;
}

# clean up
$partition_insert->finish;
$server_query->finish;
$dbh->disconnect;
