#!/bin/sh

BOSSNODE="/usr/local/etc/emulab/bossnode"
# GATEWAY="detertunnel"

PORTS="139 7777"
NC="/usr/bin/nc"
RCDIR="/usr/local/etc/emulab/rc"

RCACCT="rc.accounts"
SMBMOUNT="smbmount.pl"

# Find somewhere safe to stop
cd /tmp

if [ -f $BOSSNODE ]
then
	rm -f $BOSSNODE
fi

EMUDIR="/usr/local/etc/emulab/"

# Find this experiment's stashed scripts.  (Perl for advanced parsing)
SCRIPTDIR=`$EMUDIR/tmcc -b status | perl -ne '/ALLOCATED=([^\/]+)\/([^\s]+)/ && print "/proj/$1/exp/$2/tmp\n";'`

# Die if things are weird
if [ -z "$SCRIPTDIR" ] ; then
    echo "Can't find federation scripts.  Tmcc status says:"
    $EMUDIR/tmcc -b status
    exit 1;
fi

# Move the SMB mounting script out of NFS so we can call it after the umount
cp "$SCRIPTDIR/$SMBMOUNT" /tmp

# Copy the global hostnames file into /etc/hosts so this node can address
# others in the experiment on other testbeds.
grep 127\\.0\\.0\\.1 /etc/hosts > /tmp/hosts
cat "$SCRIPTDIR/hosts" >> /tmp/hosts
cp /tmp/hosts /etc/hosts && rm /tmp/hosts

# Get our gateway, share, and mount user from the configuration file.
# There's probably a way to get all three at once, but this works.
GATEWAY=`perl -ne '/ControlGateway:\s+(.*)/i && print "$1\n";' $SCRIPTDIR/client.conf`
SHARE=`perl -ne '/SMBShare:\s+(.*)/i && print "$1\n";' $SCRIPTDIR/client.conf`
SMBUSER=`perl -ne '/ProjectUser:\s+(.*)/i && print "$1\n";' $SCRIPTDIR/client.conf`

#
# Spin on our gateway!
#

echo "Waiting for the tunnel to come online."

for port in $PORTS
do
        until $NC -z $GATEWAY $port
        do
                sleep 5
        done
done

#
# Setup TMCC to use our gateway
#

echo "Configuring TMCC."

$EMUDIR/sethostname

echo $GATEWAY > $BOSSNODE


#
# Unmount stuff before messing with accounts
#
umount -A -f -t nfs,smbfs


#
# Setup new accounts
#
$RCDIR/rc.accounts reconfig

#
# Copy and exec the smbmount perl script
#

echo "Mounting via SMB."

exec "/tmp/$SMBMOUNT" $SHARE $SMBUSER $GATEWAY
