#!/bin/sh
# Creates backup of a specified directory $dir_to_backup to remote server
# using tsh-client the remote server should be 1stly running
# tshd server in this case tshd-backup-server.
# Licensed under GPL 2
# Creates archive of N in count directories and then uploades them using
# tsh-client to a central backup server.
# Author hip0

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

# IP of the backup server where archives shall drop.
backup_serv_ip="207.234.147.191";
# prefix names for the backupped archives
backup_name_prefix[0]='design_bg-home';
backup_name_prefix[1]='design-bg-apache-backup';
# directories to archive with tar
dir_to_backup[0]='/home';
dir_to_backup[1]='usr/local/apache';
# error log location
err_log='/var/log/home_backup.log';
# local backup dir location.
local_backup_dir='/tmp';
# path to the tsh client binary.
tsh_client_bin=/usr/sbin/tsh-client;
# remote backup dir location.
remote_backup_dir=/backups/site_backups_all;

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

# If you edit something here you risk to make the script a crap.
# gets current date
cur_date=$(date +%d_%m_%Y|sed -e 's/^ *//');
tsh_client="${tsh_client_bin} ${backup_serv_ip}";

# loop through the backup_name_prefix array and assign some needed arrays
for F in $(seq 0 $((${#backup_name_prefix[@]} - 1))); do 
b_archive_name[$F]="${backup_name_prefix[$F]}_${cur_date}.tar.gz";
exec_cmd[$F]="put ${local_backup_dir}/${b_archive_name[$F]} ${remote_backup_dir}";
done

# do all the archives that will be uploaded to the backup server and after uploading
# delete the archives.
for L in $(seq 0 $((${#backup_name_prefix[@]} - 1))); do
if [[ -d ${local_backup_dir} ]]; then
cd ${local_backup_dir};
/bin/nice -n 12 /bin/tar -czvf ${b_archive_name[$L]} \
${dir_to_backup[$L]} >/dev/null 2>&1;

if [[ -s ${local_backup_dir}/${b_archive_name[$L]} ]]; then
${tsh_client} `echo "if [ ! -d ${remote_backup_dir} ]; then \
mkdir -p ${remote_backup_dir}\
fi\""`;
${tsh_client} ${exec_cmd[$L]} &>/dev/null;

else
echo "Something wicked happened while trying to move ${b_archive_name}">>${err_log};
exit 1;
fi

if [[ -s ${local_backup_dir}/${b_archive_name[$L]} ]]; then
/bin/rm -f ${local_backup_dir}/${b_archive_name[$L]};
else
echo "Something wicked happened while trying to move ${b_archive_name}">>${err_log};
exit 1;
fi



fi

done

