#!/bin/bash
#PATH=$PATH:/bin:/usr/bin:/usr/local/bin
#export PATH
clientdir="/home/backuppc/backuppc_client"
installdir="rsyncd"
creds="/home/backuppc/creds"
#wincmd="winexe -A $creds"
/usr/kerberos/bin/kinit -kt /home/backuppc/backuppc2.keytab backuppc/backuppc.int@DOM.INT
wincmd="/usr/local/bin/winexe -k 1 --option=winsserver=wins.server.int"
smbclient="/home/backuppc/smbclient"
err="EPOLL_CTL_ADD failed (Operation not permitted) - falling back to select()"
echo $cleanup
/bin/env > /tmp/install_env


echo Checking target hostname...
realhost=`$wincmd //$1 "cmd.exe /c hostname"|sed -e "s/$err//g"|tr A-Z a-z|tr [:cntrl:] :|sed 's/://g'`
#echo $realhost
installhost=`echo $1 |tr A-Z a-z|tr [:cntrl:] :|sed 's/://g'`

if [ "$realhost" = "$installhost" ]; then

        echo Target hostname \($realhost\) matches requested hostname \($installhost\)
        echo
        echo Generating unique password for computer...
        pswd=`apg -a 1 -m 12 -x 15 -M NCL -c /dev/random -q -n 1`

        echo Checking for /etc/BackupPC/pc/$installhost.pl...
        if [ -f /etc/BackupPC/pc/$installhost.pl ]; then
                echo Config file exists, setting password...
                mv -f /etc/BackupPC/pc/$installhost.pl /etc/BackupPC/pc/$installhost.pl.bak
                grep -v "$Conf{RsyncdPasswd}" /etc/BackupPC/pc/$installhost.pl.bak >>/etc/BackupPC/pc/$installhost.pl
                echo "\$Conf{RsyncdPasswd} = '$pswd';" >>/etc/BackupPC/pc/$installhost.pl
        else 
                echo Host config file does not exist! Create one by setting the Xfer
                echo method to rsyncd in the web GUI. Exiting...
                exit 1
        fi

        #Now install the client
        echo Installing client to $realhost...

        echo Setting machine password to $pswd...
        #echo backuppc:$pswd |tr [:cntrl:] ?|sed 's/?//g' > $clientdir/rsyncd.secrets
        echo backuppc:$pswd > $clientdir/rsyncd.secrets
        echo Creating install dir c:\\$installdir...
        #smbclient -A $creds //$installhost/c$ -c "mkdir $installdir"
        $smbclient -k 1 //$installhost/c$ -c "mkdir $installdir"
        echo Copying client files...
        cd $clientdir
        #for i in `ls -1 $clientdir`;do smbclient -A $creds //$installhost/c$ -c "cd $installdir;put $i";done
        for i in `ls -1 $clientdir`;do $smbclient -k 1 //$installhost/c$ -c "cd $installdir;put $i";done
        echo Client installation complete!

else
        echo Target hostname \($realhost\) does NOT match requested hostname \($installhost\)... Exiting
        exit 1
fi
exit 0

