#!/bin/bash
#===============================================================================
#
#          FILE: syncscript
#
#         USAGE: syncscript
#
#   DESCRIPTION: Sync all the scripts, .gamerc and .functions to all the hosts
#
#  REQUIREMENTS: A corrected /etc/hosts file
#
#         NOTES: You should make a directory www/bin/ to backup the tar balls
#
#          BUGS:  ---
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Sun Jul 17 21:53:13 EDT 2011
#      REVISION: 1.0
#
#          TODO:
#
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
#set -m                                      # Enable job control

source ~/.gamerc

egrep -q "TEST|CTRL" <<< "$HOST_NAME" \
|| exec echo "Error: You can only sync from TEST/CTRL server to other hosts."

[ -f ~/bin/crontab.default ] || crontab -l > ~/bin/crontab.default
[ -f ~/.hosts ] && cat ~/.hosts ~/bin/hosts > /etc/hosts 2> /dev/null
grep -q "CTRL" <<< "$HOST_NAME" && TEST_IP="$(grep TEST ~/bin/hosts | awk '{print $1}')"

mkdir -p ~/www/bin
cd 
if grep -q "CTRL" <<< "$HOST_NAME" ; then
    ssh TEST "tar zcf www/bin.tar.gz .gamerc bin .psqlrc .functions .bash_xl .bash_profile .bashrc"
    scp TEST:~/www/bin.tar.gz ~/www/
else
    tar zcf www/bin.tar.gz .gamerc bin .psqlrc .functions .bash_xl .bash_profile .bashrc
fi

for IP in `sed -n '/BELOW/,/ABOVE/p' /etc/hosts|grep "^[0-9]"|awk '{print $1}'`;do
	echo -n "Syncing scripts to $(print_servername $IP)($IP) ... " | colorize yellow
	scp -q www/bin.tar.gz $IP:~/
	ssh $IP "tar zxf bin.tar.gz"
	sed "s/\(HOST_NAME=\"\).*/\1$(print_servername $IP)\"/" .gamerc|ssh $IP "cat > .gamerc"
	ssh $IP "rm -f bin/.*.sw* bin.tar.gz"
        cat << __EOF__ | ssh $IP "cat | sh"
[ -f ~/.hosts ] && cat ~/.hosts ~/bin/hosts > /etc/hosts 2> /dev/null
__EOF__
	echo "done" | colorize green
done

for IP in $TEST_IP;do
	echo -n "Syncing scripts to TEST($IP) ... " | colorize yellow
	scp -q www/bin.tar.gz $IP:~/
	ssh $IP "tar zxf bin.tar.gz"
	sed "s/\(HOST_NAME=\"\).*/\1TEST\"/" .gamerc|ssh $IP "cat > .gamerc"
	ssh $IP "rm -f bin/.*.sw* bin.tar.gz"
        cat << __EOF__ | ssh $IP "cat | sh"
[ -f ~/.hosts ] && cat ~/.hosts ~/bin/hosts > /etc/hosts 2> /dev/null
__EOF__
	echo "done" | colorize green
done

echo -n "Final check ... " | colorize yellow
mv www/bin.tar.gz www/bin/Ctrl-$(date +%Y%m%dT%H%M).tar.gz
cp -f ~/bin/updatectrl ~/www/bin/

#[ "$(sed -n '/BELOW/,/ABOVE/p' /etc/hosts|grep "^[0-9]"|wc -l)" == "0" ] \
#|| sendscript allall nohostname <<< "grep -q bash_xl .bashrc || sed -i '1i source ~/.bash_xl' .bashrc"
echo "OK" | colorize green

