#!/usr/bin/perl

#############################################################################
# smbmounts.pl: Setup Automounter to mount via SMB for federated experiments
# $Id: smbmount.Linux.pl,v 1.1 2008-05-18 00:09:31 faber Exp $
#

$SHARE=shift || "USERS";
$ADDR=shift || `cat /usr/local/etc/emulab/bossnode`;
$PUSER=shift || "jhickey";
$PNAME=shift || "emulab-ops";
$FSTAB="/etc/fstab";
$HOMEROOT="/users";
$PROJROOT="/proj";

chomp $ADDR;

# ADDR is probably a DNS name (and we assume so if it has letters.  mount cifs
# wants an IP address, so this hex dereferences the DNS name and converts the
# first address into the string representation of the IP.  It is, perhaps, a
# but terse.
if ($ADDR =~ /[a-z]/ ) {
    my @addrs = (gethostbyname($ADDR))[4];
    $ADDR = join(".", unpack("C4", @addrs[0]))
	if @addrs;
}


$TMCC="/usr/local/etc/emulab/tmcc";
$UMOUNT="/bin/umount";
$MOUNT="/bin/mount";
$MKDIR="/bin/mkdir";
$CP="/bin/cp";

print "Unmounting all nfs and cifs filesystems.\n";
system("$UMOUNT -a -f -t nfs,cifs"); # 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(FSTAB,">>$FSTAB") or die("Cannot Open File $FSTAB");

print FSTAB "\n# SMB Configuration Generated by smbmount.pl\n";

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


		open(PWDFILE, ">/tmp/$user.cifs_creds") || 
		    warn "Can't create credentials for $user:$!\n";
		print PWDFILE "username=$user\npassword=$pswd\n";
		close(PWDFILE);
		chmod(0600, "/tmp/$user.cifs_creds") == 1 || 
		    warn "Credential file /tmp/$user.cifs_creds may have " .
			"bad permissions:$!\n";

		print FSTAB "//$SHARE/$user\t";
		print FSTAB "$homedir\tcifs\t";
 		print FSTAB "auto,rw,credentials=/tmp/$user.cifs_creds,ip=$ADDR\t0\t0\n";

		#
		# If we are PUSER, the user assigned to mount the project
		# directory, then we add in the mount for that.  The share is
		# called proj-$PNAME where PNAME is the name of the project at
		# the mothership.  We need a second map for this since we will
		# be mounting under /proj.  We should really not use share in
		# federation.
		#

		if($user =~ m/$PUSER/i) {
			print FSTAB "//$SHARE/proj-$PNAME\t";
			print FSTAB "$PROJROOT/$PNAME\tcifs\t";
			print FSTAB "rw,credentials=/tmp/$user.cifs_creds\t0\t0\n";

		}
        }
}

close(FSTAB);

print("Mounting the cifs versions of everything\n");
system("$MOUNT -a -t cifs");
