#!/bin/sh
#Update afribin application
#This will only run svn to make sure the server has the latest revision.

cd `dirname $0`

#Functions for the afribin install checker
PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/afribin"
LANG=C
export PATH
export LANG

if [ -d /usr/local/afribin/.git ] ; then
        cd /usr/local/afribin
        #git pull
        /usr/local/afribin/sshkeysupdate
        /usr/local/afribin/srv_reports/srvrep_client_install_quiet.sh >& /dev/null < /dev/null &
        exit
fi

exit

# Big hammer
reinstall_afribin()
{
    SUBJECT="afribin re-installed - \"`hostname`\""
    EMAILID="paulo@afrihost.com"

    echo "Reinstalling afribin"
    yum -y --noplugins install wget subversion xinetd apr apr-utils
    rm -fr /usr/local/afribin.new
    echo p |svn co --username elp --password Zzbao.Otetq2  https://svn.afrihost.com/afribin/trunk /usr/local/afribin.new || {
        echo 1>&2 "SVN CO went wrong, rolling back ..."
        exit 2 
    }
    if ! svn info /usr/local/afribin.new/ ; then
        echo 1>&2 "Things went wildly wrong, rolling back ..."
        exit 2 
    fi
    # commit
    rm -fr /usr/local/afribin.last
    mv /usr/local/afribin /usr/local/afribin.last
    mv /usr/local/afribin.new /usr/local/afribin
    # yay, new afribin!
    # /usr/local/afribin/upab # infloop!

    cd /usr/local/afribin/maintenance/nagios/ 
    /usr/local/afribin/maintenance/nagios/nagios_check 
    service xinetd restart 
    rm -r /usr/local/afribin.last </dev/null
    echo "Subject: $SUBJECT
To: $EMAILID

afribin was re-installed on `hostname`"  | /usr/sbin/sendmail "$EMAILID"
}

#Will update the binary files for afribin
./chsvnroot -n . #Wipe any usernames or passwords from the svn repository
if [ -d ~/.subversion/auth/svn.simple ] ; then #Make sure we don't keep any subversion passwords or usernames on the system
  rm -rf ~/.subversion/auth/svn.simple
fi
if ./activeupdate; then
  #if the update was successfull rebuild the ssh keys
  /usr/local/afribin/sshkeysupdate
  /usr/local/afribin/srv_reports/srvrep_client_install_quiet.sh >& /dev/null < /dev/null &
else
  reinstall_afribin
fi

