#!/bin/bash
##########################################################
# Database downloader script via SFTP protocol           
# Usage: ./dtb-sftp (now)                                
#           
# Changelog:                                                                                     
# rpm68	- removing german text
#		- adding chmod 777 for syncstatus
# rpm71 - using DTBconfigFile.xml
# rpm75 - adding 3s sleep before starting the backup
# rpm77 - moving from /var/tmp/dtb into /var/pgsql/dtb_config/
##########################################################

# This script is set to run in every second via crontab added in the Dtb HA script. 
# But it will execute actions only at the time set in the sftpserver file.
# The sftpserver file will be saved to haipsetup.xml only when DTB is stopped (in Dtb HA script).

# Import definitions
CMD=$(basename $0)
if [ -f /opt/dtb/bin/_common_definitions ]; then
	. /opt/dtb/bin/_common_definitions
else
	logger -t $CMD -p ERROR -s "The /opt/dtb/bin/_common_definitions file does not exist, exiting the script..."
	exit 1
fi

outputInFile () {
	chmod 666 /var/pgsql/dtb_config/syncstatus; 
	sed -i '2d' /var/pgsql/dtb_config/syncstatus;
	echo $1>>/var/pgsql/dtb_config/syncstatus;
}

stime=$(readConfigXML "sftp-time")
ctime=$(date +"%H:%M") # get the current time in hh:mm format

if ([ "$1" == "now" ] || [ "$stime" == "$ctime" ]); then
	
	if [ -f $CONFIG_FILE ]; then # This file is created by the portal
		IP=$(readConfigXML "sftp-ip")
		usr=$(readConfigXML "sftp-user")
		pwd=$(readConfigXML "sftp-password")
		pwd=$(echo $pwd | openssl aes-256-cbc -a -d -salt -k '1825e09252d7c6f66f5e1be666154306')
		pth=$(sed 's/ /\\ /g' <<< "$(readConfigXML "sftp-path")") # add \ before spaces
		if [ ! ${pth: -1} == "/" ]; then # add slash if there is no slash at the end
			pth=$pth/
		fi
	else
		plog "ERROR: The $CONFIG_FILE file does not exist, exiting the script..."
		outputInFile "The $CONFIG_FILE file does not exist"
		exit 1
	fi
	
	# Check if IP format is 0..255.0..255.0..255.0..255
	if [ `echo $IP | grep -o '\.' | wc -l` -ne 3 ]; then
		plog "ERROR: Exiting with: Invalid IP: does not contain 3 dots!"
		outputInFile "Invalid IP: does not contain 3 dots!"
		exit 1;
	elif [ `echo $IP | tr '.' ' ' | wc -w` -ne 4 ]; then
		plog "ERROR: Exiting with: Invalid IP: does not contain 4 octets!"
		outputInFile "Invalid IP: does not contain 4 octets!"
		exit 1;
	else
		for OCTET in `echo $IP | tr '.' ' '`; do
				if ! [[ $OCTET =~ ^[0-9]+$ ]]; then
						plog "ERROR: Exiting with: Invalid IP: an octet is not numeric!"
						outputInFile "Invalid IP: an octet is not numeric!"
						exit 1;
				elif [[ $OCTET -lt 0 || $OCTET -gt 255 ]]; then
						plog "ERROR: Exiting with: Invalid IP: an octet in not in range 0-255!"
						outputInFile "Invalid IP: an octet in not in range 0-255!"
						exit 1;
				fi
		done
	fi

	plog "SFTP download START."

	# The files will be downloaded into the import directory
	cd $DTB_DRBD_SHARE/DTBServer/import

	export expprompt=""
	export secretpasswd=$pwd
	export theexptimeout=15

	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.nam;
	sleep 5
	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.nax
	sleep 5
	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.rnr;
	sleep 5
	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.rnx
	sleep 5
	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.t9i
	sleep 5
	/opt/dtb/bin/auto-ssh-passwd.sh sftp $usr@$IP:$pth*.dtb
	sleep 5

	plog "SFTP download FINISH."
	plog "The downloaded files are: $(ls -dm * | tr -d ' ')"
	
	#set user/group of all files
	chown -R $DTB_USER:$DTB_GROUP $DTB_DRBD_SHARE/DTBServer/import
	chmod 751 $DTB_DRBD_SHARE/DTBServer/import
	
	plog "Restarting DTB via dtb-reconfigure script."
	
	# Run the reconfigureing script which will copy the files into winedir and restart DT. 
	. /etc/profile
	export HOME=/root
	/opt/dtb/bin/dtb-reconfigure
	
	# Update the syncstatus file regarding to the result
	updated_state=$?
	
	# Verify if the syncstatus file exsists. If not create it.
	if [ ! -f $DTB_SYNCSTATUS ]; then
		echo "" > $DTB_SYNCSTATUS
		plog "File syncstatus created."
	fi
	
	chmod 777 $DTB_SYNCSTATUS
	
	d=$(date +%Y-%m-%d)" "$(date +%H:%M:%S)
	
	if [ $updated_state -eq 0 ]; then # No DTB restart performed
		echo "Successfully completed at $d with SFTP (files were not changed)." > $DTB_SYNCSTATUS;
	elif [ $updated_state -eq 2 ]; then # The import directory was changed
		echo "Successfully completed at $d with SFTP." > $DTB_SYNCSTATUS;
	elif [ $updated_state -eq 3 ]; then # The import directory was empty
		echo "Failed at $d with SFTP. No files downloaded." > $DTB_SYNCSTATUS;
	elif [ $updated_state -eq 4 ]; then # The import directory was changed but the mandatory files are missing
			echo "Failed at $d with SFTP, because one or more mandatory files couldn't be downloaded." > $DTB_SYNCSTATUS;
	fi	
	
	status="$(cat $DTB_SYNCSTATUS)"
	plog $status
	
	# wait before restarting the DTB. Otherwise the previous syncstatus file is backed up!
	sleep 3
	
fi
