#!/bin/sh
# site_backups.sh.
# This script is licensed under the General Public License ver. 2.0
# See http://www.gnu.org/licenses/gnu.txt for details.
# For bugs and suggestions mail to: hipodilski@dahmer.vistech.net


################## Configure Here #################

# IP of the backup server where archives shall drop.
BACKUP_SERV_IP="207.234.147.191";

# path to the tar binary.
TAR_BIN=/bin/tar;

# tar options.
TAR_OPTS='-czvf';

# remote backup dir location.
REMOTE_BACKUP_DIR=/backups/site_backups_all;

# path to the tsh client binary.
TSH_CLIENT_BIN=/usr/sbin/tsh-client;


# mode ( interactive|non-interactive, 1|0 )
INTERACTIVE=0;

# directory locations to be into the archive
BACKUP_LOCATION[0]=/home/customusers/est8scouk; 
BACKUP_LOCATION[1]=/home/customusers/sclangenthalch;
BACKUP_LOCATION[2]=/home/customusers/bulgariatravelorg;

####################################################

array_length=$((${#BACKUP_LOCATION[*]} - 1));

# If you edit something here you risk to make the script a crap.
TSH_CLIENT="$TSH_CLIENT_BIN $BACKUP_SERV_IP";

BACKUP_FILE_NAME=`date +%k_%d_%m_%Y|sed -e 's/^ *//'`.tar.gz;


chk_variables_def () {

if [ -z "$BACKUP_SERV_IP" ] || [  -z "$TAR_BIN" ] ||\
[ -z "$TAR_OPTS" ] ||\
[ -z "$REMOTE_BACKUP_DIR" ] ||\
[ -z "$TSH_CLIENT_BIN" ] ||\
[ -z "$INTERACTIVE" ]; then
echo "Missing Variable !!! Fatal Error occured !" >> /var/log/site_backups-fatal.log;
exit 1;
fi

}

construct_backup_names () {

array_length=$((${#BACKUP_LOCATION[*]} - 1));
for F in $(seq 0 ${array_length}); do

SITE_NAME[$F]=${BACKUP_LOCATION[$F]}-${BACKUP_FILE_NAME};

done

}

# create backups func.
create_site_backup () {

if [ $INTERACTIVE -ne 0 ]; then

echo "Creating site backups and archiving it's content ...";

fi

for L in $(seq 0 ${array_length}); do

nice -n 10 $TAR_BIN $TAR_OPTS ${SITE_NAME[$L]} ${BACKUP_LOCATION[$L]} &>/dev/null;

done

}

chk_rem_backup_dir_existence () {
if [ $INTERACTIVE -ne 0 ]; then

echo "Checking for remote: $REMOTE_BACKUP_DIR existence ...";

fi

$TSH_CLIENT `echo "if [ ! -d $REMOTE_BACKUP_DIR ]; then \
mkdir -p $REMOTE_BACKUP_DIR\
fi\""`;

}


# upload .tar.gz archives func. 
upload_backup () {

for i in $(seq 0 ${array_length}); do
if [ $INTERACTIVE -ne 0 ]; then

echo "Putting The backupped archives into remote: $REMOTE_BACKUP_DIR ...";


EXEC_CMD[$i]="put ${SITE_NAME[$i]} ${REMOTE_BACKUP_DIR}";
echo "${TSH_CLIENT} ${EXEC_CMD[$i]}";
echo "rm -f ${SITE_NAME[$i]}";
${TSH_CLIENT} ${EXEC_CMD[$i]};
rm -f ${SITE_NAME[$i]};

else

EXEC_CMD[$i]="put ${SITE_NAME[$i]} ${REMOTE_BACKUP_DIR}";
$TSH_CLIENT ${EXEC_CMD[$i]} &>/dev/null;
rm -f ${SITE_NAME[$i]};

fi

done

}

# Main function.
main () {

chk_variables_def;
construct_backup_names;
create_site_backup;
chk_rem_backup_dir_existence;
upload_backup;
}

main;
