#!/afs/athena/contrib/perl/perl

unshift(@INC,"/afs/athena.mit.edu/user/m/a/marc/perl");

require 'hesiod.pl';

sub usage {
    die "usage: $0 account\n\twhere account is sipb[0-7]\n";
}

$account = shift(@ARGV) || &usage;

if ($account !~ /^sipb[0-7]$/) { &usage; }

$fs = "/bin/athena/fs";
$vos = "/bin/athena/vos";
if (! -x $vos) {
    $vos = "/afs/athena.mit.edu/system/afsuser/@sys/bin/vos";
    if (! -x $vos) {
	die "vos isn't in any of the usual places\n";
    }
}
$src = "/afs/sipb.mit.edu/project/guests/prototype";
$dst = "/afs/sipb.mit.edu/user/$account";

@pwents = &hes_resolve($account,"passwd");

$auid = (split(/:/,$pwents[0]))[2] || die "Couldn't get uid for $account.\n";

print <<EOF;
Cleaning SIPB guest account $account.
Make sure you have system:administrators tokens!
Are you sure you want to obliterate the account $account?
EOF
    ;

print "Enter YES to do it: ";

$ans = <>;

if ($ans ne "YES\n") {
    die "Cancelled.\n";
}

print "\n",$pwents[0],"\n";

open(VOS, "$vos examine user.$account -c sipb.mit.edu |")
    || die "vos examine failed.\n";

while(<VOS>) {
    if (/server\s+(\S+)\s+partition\s+\/vicep(.)\s+RW/) {
	$server = $1;
	$partition = $2;
    }
}

if (!$server || !$partition) {
    die "vos examine didn't return a RW partition location.\n";
}

print "\nRemoving and recreating user volume...\n";

system("$vos remove $server $partition user.$account -c sipb -verbose")
    && die "vos remove failed.\n";
system("$vos create $server $partition user.$account -c sipb -verbose")
    && die "vos create failed.\n";
system("$fs checkv")
    && die "fs checkv failed.\n";

print "\nSetting acl...\n";

system("$fs sa $dst -clear $account all system:anyuser rl system:administrators write")
    && die "fs sa ~$account failed.\n";

print "\nCopying files...\n";

system("(cd $src;tar cf - .)|(cd $dst;tar xpf -)")
    && die "tar failed.\n";

print "\nCreating ~/Mail...\n";

mkdir("$dst/Mail", 0700) || die "mkdir failed.\n";

print "\nSetting file ownerships...\n";

# I could not run chown here, but I'm lazy.
system("chown -R $auid $dst")
    && "chown failed.\n";

system("$fs sa $dst/Mail -clear $account all")
    && die "fs sa ~$account/Mail failed.\n";

system("$fs setquota $dst 17500") &&
    warn "fs setquota failed, but it lies, sometimes.\n";

print "\nBacking up homedir...\n";

system("$vos backup user.$account -c sipb -verbose")
    && die "vos backup failed.\n";

print "\n";

system("$fs listquota $dst");
system("ls -laR $dst");

print "SIPB guest account $account cleaned.\n";
