#!/usr/local/bin/perl

#############################################################################
# smbmounts.pl: Setup Automounter to mount via SMB for federated experiments
# $Id: smbmount.pl,v 1.3 2007-09-27 02:50:14 jhickey Exp $
#

$ADDR="users.isi.deterlab.net";
$TMCC="/usr/local/etc/emulab/tmcc";
$SHARE="USERS";
$FSTAB="/etc/fstab";
$HOMEROOT="/users";
$AMDROOT="/auto";
$AMDMAP="/etc/amd.users";

$UMOUNT="/sbin/umount";
$MOUNT="/sbin/mount";
$MKDIR="/bin/mkdir";
$CP="/bin/cp";
$KILLALL="/usr/bin/killall";
$AMD="/usr/sbin/amd";

print "Killing amd.\n";
system("$KILLALL amd");

print "Unmounting all nfs and smb filesystems.\n";
system("$UMOUNT -A -f -t nfs,smbfs"); # or die("Failed to unmount NFS");

# Backup the fstab so we can run multiple times
if (! -f "$FSTAB.bak") {
	system("$CP $FSTAB $FSTAB.bak") && die("Unable to backup $FSTAB");
} else {
	system("$CP $FSTAB.bak $FSTAB") && die("Unable to restore $FSTAB");
}

open(TM, "$TMCC accounts windows |") or die("Failed to execute TMCC");
open(CONFIG, ">/etc/nsmb.conf") or die("Failed to open /etc/nsmb.conf");
open(MAP, ">$AMDMAP") or die("Failed to open /etc/amd.users");
open(FSTAB,">>$FSTAB") or die("Cannot Open File $FSTAB");

print FSTAB "\n# SMB Configuration Generated by smbmount.pl\n";
print MAP "# AMD Configuration Generated by smbmount.pl\n";
print CONFIG "# SMB Configuration Generated by smbmount.pl\n\n";
print CONFIG "[$SHARE]\naddr=$ADDR\n\n";

while(<TM>) {
        if (/ADDUSER LOGIN=(\S+) PSWD=(\S+) UID=(\d+) GID=(\d+).*HOMEDIR=(\S+) / ) {
                $user = $1;
                $pswd = $2;
                $uid  = $3;
                $gid  = $4;
                $homedir = $5;

		$userlc = $user;
		# SMB demands upper case.
		$user =~  tr/a-z/A-Z/;
		my $pass = `smbutil crypt '$pswd'`;

                print CONFIG "[$SHARE:$user]\npassword=$pass\n";
		
		if(! -d "$AMDROOT$homedir") {
			system("$MKDIR -p $AMDROOT$homedir") && die("Failed to make directory");
		}

		print FSTAB "//$user\@$SHARE/$user\t";
		print FSTAB "$AMDROOT$homedir\tsmbfs\t";
 		print FSTAB "noauto,rw,-N,-f744,-d755,-u$uid,-g$gid\t0\t0\n";

		print MAP "\n$userlc type:=program;fs:=$AMDROOT$homedir;\\\n";
		print MAP "mount:=\"$MOUNT mount $AMDROOT$homedir\";\\\n";
		print MAP "unmount:=\"$UMOUNT unmount $AMDROOT$homedir\";";
        }
}

close(CONFIG);
close(FSTAB);
close(MAP);

print "Starting the automounter: $AMD -l syslog -a $AMDROOT $HOMEROOT $AMDMAP\n";
system("$AMD -l syslog -a $AMDROOT $HOMEROOT $AMDMAP") && die("Unable to start amd");
