#!/bin/sh
# gen_new-rsync_job_conf.sh is to for easy new job creation to /opt/imal/etc/rsync.conf
# variables to get from command line
# Script to add new rsync records to /opt/imal/etc/rsync.conf
# later enable the job via lets say
##  1,31 * * * * /usr/bin/perl /opt/imal/bin/rsync.pl $name

get_src=$1
get_src_nfs=$2
put_src=$3
put_src_nfs=$4
put_server=$5;
name=$6;
desc=$7;
home='/home/c5280383';
exclude='.snapshot;.ssh';
conf='/opt/imal/etc/rsync.conf';
t_conf="$home/rsync.conf";

clean_conf='yes';
# check if args passed to script
if [ "$get_src" ] && [ "$get_src_nfs" ] && [ "$put_src" ] && [ "$put_src_nfs" ] && \
[ "$put_server" ] && [ "$name" ] && [ "$desc" ]; then
# check if mounted get_src and get_src_nfs dir exists
nslookup $put_server >/dev/null 2>&1
##echo $?
##echo "mount |grep -i $(echo $get_src| cut -d ':' -f2) |wc -l"
if [[ "$?" == "0" ]] && [[ "$(mount |grep -i $(echo $get_src| cut -d ':' -f2) |wc -l)" == '1' ]];  then

echo '[ OK ] mounts are fine ... proceeding';
else
echo "[ FAILED ] Some of the $get_src / $get_src_nfs / $put_src / $put_src_nfs / $put_server / $name / $home are not mounted or present ,. Exiting ..."
##exit 1;
fi

fqdn=$(nslookup $(hostname)|grep Name | awk ' { print $2 }');
h0=$(echo $get_src | cut -d ":" -f 1);
h1=$(echo $put_src | cut -d ":" -f 1);
dest_src=$(nslookup $put_src|grep Name | awk ' { print $2 }');
echo "[ OK ] Creating $conf backup in ~/$conf-`date +%d-%m-%y`.bak";
echo "cp -rpf $conf $home/$conf-`date +%d-%m-%y`.bak"
cp -rpf $conf $home/$conf-`date +%d-%m-%y`.bak
echo "[ OK ] Generating $t_conf";
if [ "$clean_conf" == 'yes' ]; then
cat /dev/null  > $t_conf
fi
cat $conf >$t_conf
echo "#Added to rsync.conf - $(date +%d-%m-%y)" >>$t_conf
echo "[$name] $description" >> $t_conf
echo "bwlimit|128000" >> $t_conf
echo "get_server|$fqdn" >> $t_conf
echo "get_nfs|$get_src" >> $t_conf
echo "get_dir|$get_src_nfs" >> $t_conf
echo "put_server|$put_server" >> $t_conf
echo "put_nfs|$put_src" >> $t_conf
echo "put_dir|$put_src_nfs" >> $t_conf
echo "exclude|$exclude" >> $t_conf
##echo "exclude|.snapshot" >> $t_conf
echo "[ OK ] Completed";
echo "Please always review $conf to make sure no problems with it";
echo "!!! To override with new config run (ON YOUR OWN RESPONSIBILITY) !!!:";
echo "cp -rpf $t_conf $t_conf";

else

echo -e "Syntax: SRC_DIR SRC_DIR_NFS_VOL DST_SRC DST_SRC_NFS PUT_SERVER NAME CRON_TITLE_NAME DESCRIPTION\n"
echo -e 'i.e.:  src_server:/vol_name1 /repo/src/dir/to/sync dst_server:/volume_name2 /repo/dst/dir/to/sync hec03v027987.stl.hec.sap.biz rsync.pl_CRON_argument_name Desription'
echo 'Sample use';
echo './gen_rsync_conf.sh hec07fi0319:/vol1_s4hana_repomaster /repo/repo/s4hana hec07fi0319:/vol1_s4hana_repomaster /repo/repo/s4hana/data hec03v027987.stl.hec.sap.biz set_SYDDBA description';
echo 'To enable in cron use smth like';
echo "1,31 * * * * /usr/bin/perl /opt/imal/bin/rsync.pl $name";
echo -e "\nTo add excludes edit the script \$exclude option and add them";


fi

