#!/bin/bash
# this "weekly_sync.sh" is used for CHOWTAISENG weekly_sync from UAT to PRD system. Need to alter EXPORT dir & schema password & server IP & server password if used for other systems.
# usage
# ./weekly_sync

cd /var/EPM2/EXPORT
rm -rf * &
PID1=$!
wait $PID1
echo "1/9: OLD EXPORT DELETED!"

/usr/sap/EPM/HDB01/exe/hdbsql -i 01 -u EPM -p EPM_user_2022 "EXPORT EPM.\"*\" AS BINARY INTO '/var/EPM2/EXPORT' WITH REPLACE" &
PID2=$!
wait $PID2
echo "2/9: EXPORT DONE!"

cd /var/EPM2/EXPORT/export/EPM; rm -rf "TC"; rm -rf "$D"; cd /var/EPM2/EXPORT/index/EPM; rm -rf "T1"; rm -rf "$M" &
wait $!
echo "3/9: TC_$D_T1_$M REMOVED!"
cd /var/EPM2/EXPORT
tar zcf PRD.tar.gz * &
PID3=$!
wait $PID3
MD5=`md5sum PRD.tar.gz`
echo "4/9: PRD.tar.gz PACKED!"

sshpass -p CTScfs-hanatest159357# ssh root@192.168.167.52 << endofssh1
cd /var/EPM2/EXPORT; rm -rf * &
PID4=$!
wait $PID4
endofssh1
echo "5/9: OLD SSH_EXPORT DELETED!"

sshpass -p CTScfs-hanatest159357# scp PRD.tar.gz 192.168.167.52:/var/EPM2/EXPORT &
PID5=$!
wait $PID5
echo "6/9: SCP DONE!"

sshpass -p CTScfs-hanatest159357# ssh root@192.168.167.52 << endofssh2
cd /var/EPM2/EXPORT; tar zxf PRD.tar.gz &
PID6=$!
wait $PID6
md5sum PRD.tar.gz > md5_copy
/usr/sap/EPM/HDB01/exe/hdbsql -i 01 -u EPM -p EPM_user_2022 "IMPORT EPM.\"*\" AS BINARY FROM '/var/EPM2/EXPORT' WITH REPLACE" &
PID7=$!
RESULT1=$?
echo "$RESULT1" > result1
wait $PID7
dateStr=`date '+%F_%H'`
/usr/sap/EPM/HDB01/exe/hdbsql -i 01 -u EPM -p EPM_user_2022 "IMPORT EPM.GROUPS,EPM.GROUP_ACCESS_PROFILE,EPM.GROUP_SYSTEM_PROFILE,EPM.GROUP_USER,EPM.USERS,EPM.USER_ACCESS_PROFILE,EPM.USER_SYSTEM_PROFILE,EPM.SYSTEM_PROFILE,EPM.SHEET_PERM AS BINARY FROM '/var/EPM2/BACKUP/HANA/data/SCHEMA_BACKUP_HOURLY/$dateStr' WITH REPLACE" &
PID8=$!
RESULT2=$?
echo "$RESULT2" > result2
wait $PID8
endofssh2

sshpass -p CTScfs-hanatest159357# scp 192.168.167.52:/var/EPM2/EXPORT/md5_copy . &
wait $!
sshpass -p CTScfs-hanatest159357# scp 192.168.167.52:/var/EPM2/EXPORT/result1 . &
wait $!
sshpass -p CTScfs-hanatest159357# scp 192.168.167.52:/var/EPM2/EXPORT/result2 . &
wait $!

MD5=`md5sum PRD.tar.gz`
MD5_COPY=`cat md5_copy`
echo "$MD5"
echo "$MD5_COPY"
if [[ "$MD5" == "$MD5_COPY" ]]; then
        echo "7/9: MD5 SAME!"
else
        echo "7/9: MD5 DIFFERENT!"
fi

RESULT1=`cat result1`
if [[ "$RESULT1" == 0 ]]; then
        echo "8/9: IMPORT SUCCESSFULLY!"
else
        echo "8/9: IMPORT FAILED!"
fi

RESULT2=`cat result2`
if [[ "$RESULT2" == 0 ]]; then
        echo "9/9: USER PROPERTY RECOVERED!"
else
        echo "9/9: USER PROPERTY RECOVER FAILED!"
fi

echo "SYNC DONE!"

