#!/bin/bash

# bash -vx
tmpdate=`date +%Y%m%d_%H%M%S`
db=AERO.FDB
dbpath=/var/ksrs/base
dbuser=SYSDBA
dbpassword=masterkey

#Firebird path
fb_root=/usr
#fb_root=/opt/fb25ss
fb_bin=${fb_root}/bin

bkpath=/var/ksrs/base/restore

logfile=$dbpath/restore.log
lock=$dbpath/restore.lock

tmp_db=$tmpdate-$db

backupexist=`find $bkpath -type f | wc -l`

msg()
{
	echo "$1"
	echo "`date '+%F %T'`:  $1" >> $logfile
}

msg1()
{
	echo "$1"
	echo "$1" >> $logfile
}

firebird_start()
{
	msg "starting Firebird..."
	service firebird-superserver start || service firebird start
	msg "starting Firebird...DONE"
}
firebird_stop()
{
	msg "stopping Firebird..."
	service firebird-superserver stop || service firebird stop
	msg "stopping Firebird...DONE"
}
collector_start()
{
	msg "starting Collector..."
	systemctl start lemz-snmp-collector
	msg "starting Collector...DONE"
}
collector_stop()
{
	msg "stopping Collector..."
	systemctl stop lemz-snmp-collector
	msg "stopping Collector...DONE"
}

db_restore()
{
	collector_stop

	msg "unpacking backup..."
	cd $bkpath && ls -t | xargs -i /usr/bin/xz -dv '{}'
	msg "unpacking backup...DONE"

	msg "restoring backup..."
	ls -t | xargs -i ${fb_bin}/gbak -r -v -rep '{}' 127.0.0.1:$dbpath/$db -user $dbuser -pas $dbpassword && msg "database successfully restored" || msg "error restoring database!"
	msg "restoring backup...DONE"

	msg "cleaning up..."
	ls -t | xargs -i rm -fv '{}'
	msg "cleaning up...DONE"

	collector_start
}

if [ -e $lock ]; then
	msg "Backup already running"
else
	touch $lock

	msg1 ""
	msg1 "================================================"
	msg1 "$(date +'%d-%b-%Y %R')"
	if [ $backupexist -eq 0 ]; then	
	      msg "backup file not exist, restore is not possible!"
	else      
	      if [ -f $dbpath/$db ]; then
		      msg "destination database exist, creating backup copy..."
		      firebird_stop
		      mv -f -T $dbpath/$db $dbpath/$tmp_db && msg "file $tmp_db created"
		      firebird_start
		      msg "destination database exist, creating backup copy...DONE"

		      if [ -f $dbpath/$tmp_db ]; then
			      db_restore
			      if [ -f $dbpath/$db ]; then
				      rm -f $dbpath/$tmp_db
			      fi
		      else
			      msg "failed to create a backup copy of existing database, cannot continue with restore!"
		      fi
	      else
		      db_restore
	      fi
	fi
	rm -f $lock
	msg "finished. you can continue your work now. or go home." 
fi
