#!/bin/bash

. /etc/profile

function log_gendb() {
	echo `date` AutoGENDB $$ $* >> /var/log/webservice/initADP_RMXdb.log
	logger $0 AutoGENDB $$ $*
}

function exec_gendb() {

    #OSFOURK-5296: V8R1 FI REGEN-GENDB script should not run on Survivable units
	/opt/webservice/scripts/is_ape
	if [ $? -eq 1 ];then
        log_gendb "Survivable unit detected..."
        #OSFOURK-9667 - V8 R2 FI: Delete REGEN files from foreign systems
        log_gendb "Clean up other REGEN files..."
        cd /instmedia/config/
        rm -v *.samtxt  *.zip
        cd /var/tmp/
        rm -v *.samtxt  *.zip 
        cd /var/opt/firstinstall/
        rm -v *.samtxt  *.zip 
        cd /var/tmp/firstinstall-inst/
        rm -v *.samtxt  *.zip
        return 0
	fi
    
    #OSFOURK-14330 - wait max 1h for indication that Assistant Install finished to avoid overlap
    log_gendb "Waiting for Assistant Installation to finish. Auto GENDB will be done afterwards ..."
    i=360
    while [ $i -gt 0 ]; do
       sleep 10
       [ -e /dev/.assistant.install.finished ] && break
       i=$(($i - 1))
    done
    if [ $i -gt 0 ]; then
        log_gendb "Assistant Installation finished. Will now wait 10 minutes to make sure no SWA activities are going on ..."
    else
        log_gendb "WARNING : Assistant Installation still not finished after 1 hour. Will now continue and wait 10 minutes to make sure no SWA activities are going on. This includes Assistant Installation ..."
    fi
    sleep 60
    i=354
    c=54
    while [ $c -gt 0 ]; do
        sleep 10
        #if SWA.lock appears within 10 minutes since last time it was present then start counting again down from 10 minutes
        [ -e /var/opt/Assistant/data/SWS/lock/SWA.lock ] && c=60
        c=$(($c - 1))
        i=$(($i - 1))
        #if overall timeout of 1 hour is reached and SWA is still doing something then continue in any case with GENDB
        [ $i -gt 0 ] || break
    done
    if [ $i -gt 0 ]; then
        log_gendb "Assistant SWA is idle. Will now start Auto GENDB ..."
    else
        log_gendb "WARNING : Assistant SWA is still not idle after 1 hour. Will now anyway start Auto GENDB ..."
    fi
    
    #[OSFOURK-18352] Fi with V10_R1.10_RC2 on GSD (B primary) unsuccessful - Node B has status Y
    log_gendb "Will now run an EXE-UPDAT:BP,ALL; to make sure GP CODEW generated by Assistant does not get lost ..."
    time ( echo -e "cha-funct:slang=eng;\nexec-updat:bp,all;" | sshr /opt/bin/dipas_batch )
    log_gendb "EXE-UPDAT:BP,ALL; finished."

	SAMTXT=""
	rm -rf /tmp/SWU.samtxt

	pushd /instmedia/config
	find . -type f | grep -i zip$ | xargs -n 1 unzip
	for allsamfiles in $(find . -type f | grep -i samtxt$); do
		nominus=${allsamfiles//-/}
		nominus=${nominus//_/}
		nominus=`echo $nominus | tr '[:upper:]' '[:lower:]'`
		for allmacs in $(cat /sys/class/net/eth*/address | sed -e s/://g | tr '[:upper:]' '[:lower:]'); do
			[[ "x$nominus" =~ $allmacs ]] && SAMTXT=$allsamfiles
		done
	done
	[ -n "$SAMTXT" ] && {
		log_gendb "Found REGEN File : $SAMTXT"
		cp $SAMTXT /tmp/SWU.samtxt
		#OSFOURK-9667 - V8 R2 FI: Delete REGEN files from foreign systems
		log_gendb "Clean up other REGEN files..."
		SAMTXT_STRIPED=`echo $SAMTXT | sed s/".\/"//`
		cd /instmedia/config/
		ls *.samtxt  *.zip | grep -v $SAMTXT_STRIPED | xargs rm -v
		cd /var/tmp/
		ls *.samtxt  *.zip | grep -v $SAMTXT_STRIPED | xargs rm -v
		cd /var/opt/firstinstall/
		ls *.samtxt  *.zip | grep -v $SAMTXT_STRIPED | xargs rm -v
		cd /var/tmp/firstinstall-inst/
		ls *.samtxt  *.zip | grep -v $SAMTXT_STRIPED | xargs rm -v
	}
	popd
	
	[ -e /tmp/SWU.samtxt ] || {
		log_gendb "No matching REGEN file found."
		#OSFOURK-9667 - V8 R2 FI: Delete REGEN files from foreign systems
		log_gendb "Clean up other REGEN files..."
		cd /instmedia/config/
		rm -v *.samtxt  *.zip
		cd /var/tmp/
		rm -v *.samtxt  *.zip 
		cd /var/opt/firstinstall/
		rm -v *.samtxt  *.zip 
		cd /var/tmp/firstinstall-inst/
		rm -v *.samtxt  *.zip
		return 0
	}
	
	#use AMO UPDAA instead of UPDAT
	sed -i -e s/-UPDAT:/-UPDAA:/ /tmp/SWU.samtxt
	#automatically replace with right SWU header
	sed -i -e "s/C001 \*P30252............................................./C001 *P30252B5200B00100P30252B5200B00100P30252B5200S00100/" /tmp/SWU.samtxt
	#automatically replace with right ADS header
	sed -i -e "s/B001 \*P30252............................................./B001 *P30252B5200A00100P30252B5200A00100P30252B5200D00100/" /tmp/SWU.samtxt

	chattr +i /var/opt/webservice/Install.running

	localcc=
	remoteres=
	localres=
	RMXproc=

	#stop standby CC during DB gen
	IS_DUPLEX=false
	/opt/webservice/scripts/is_duplex
	[ $? -eq 1 ] && IS_DUPLEX=true
    REMOTE_STOPPED=false
    
    log_gendb "Waiting for local CC to get ready ..."
	i=0
	k=9999
	while [ $i -lt 900 ]; do
		sleep 10
        
        [ "x$remoteres" = "x" ] && {
            #determine which CC am I running here
            virsh list | grep -q CCA && { localcc=CCA; localres=rsc4k_cca; remoteres=rsc4k_ccb; RMXproc=; }
            virsh list | grep -q CCB && { localcc=CCB; localres=rsc4k_ccb; remoteres=rsc4k_cca; RMXproc='--ccb'; }
        }
        
        [ "x$localcc" = "x" ] && {
            log_gendb "Local CC is not running yet ..."
            continue
        }
        
        $IS_DUPLEX && {
            $REMOTE_STOPPED || {
                crm resource status $remoteres 2>&1 | grep "is running on" && {
                    log_gendb "Stopping $remoteres ..."
                    crm --wait resource stop $remoteres
                    REMOTE_STOPPED=true
                    #OSFOURK-19029 - Fi with V10_R1.14 on GSD (B primary) - no codeword in RMX
                    #also reload the complete system so that the other CC reads the previously saved CODEW
                    #(Note: during Y state the standby CC is not synchronized with the Active CC, therefore the CODEW added by Assistant was having an effect only on the Active CC)
                    #the simplest way to reload is to restart completely the local CC
                    log_gendb "Restarting $localres to make sure it reads the GP CODEW ..."
                    crm --wait resource stop $localres
                    crm --wait resource start $localres
                    log_gendb "$localres restart done."
                }
            }
        }
        
		grep "7-Segment Display" /var/log/libvirt/qemu/$localcc.log | tail -n 1
		grep "7-Segment Display" /var/log/libvirt/qemu/$localcc.log | tail -n 1 | grep -q 0xae && break
		grep "7-Segment Display" /var/log/libvirt/qemu/$localcc.log | tail -n 1 | grep -q 0x77 && break

		#OSFOURK-4397 V8R1 RLC update fails if display of SWU CPU load DIAG on 7-Seg is enabled
		# additional check - if for 5 minutes in one of the last 5 lines we find the 0x77 or 0xae then continue
		( ( grep "7-Segment Display" /var/log/libvirt/qemu/$localcc.log | tail -n 5 | grep -q 0x77 ) || ( grep "7-Segment Display" /var/log/libvirt/qemu/$localcc.log | tail -n 5 | grep -q 0xae ) ) && {
			if [ $k -eq 9999 ]; then
				k=0
			else
				k=$(($k + 10))
				[ $k -gt 300 ] && break
			fi
		}

		i=$(($i + 10))
	done
	[ $i -lt 900 ] || {
		log_gendb "ERROR: Timeout while waiting for $localcc to get ready"
		return 1
	}
	
    #OSFOURK-16108 FI V10 R0.28 - RMX shows INCONSISTENCY in your contracted software
    # in this point in the code before the OSFOURK-16108 was raised, there used to be some DEBUGs executed here to skip CODEW checks during GENDB
    # still, since the OSFOURK-14330 we do not need the DEBUGs anymore as Assistant should already have generated a valid Grace Period CODEW at the time the execution reaches this point

	log_gendb "Doing GENDB ..."
	
	#special situation - do not allow others to run UPDAT in this time
	touch /dev/.gendb.renameupdat
    #OSFOURK-9443 - create special stapel for the controlled reload during AutoGendb
    cat > /opt/dscxl/share/stapel << '_EOF_STAPEL_RELOAD_'
/*!=!LANG_ENG
CHA-FUNCT:SLANG=ENG;
/*!=!CHECK_ON
DISP-SIGNL:SYSTEM;
/*!=!BEFORE_ADP_RESTART
EXE-REST:SYSTEM,RELOAD;
/*!=!AFTER_ADP_RESTART
/*!=!CHECK_ON
/*!=!LANG_ENG 
CHA-FUNCT:SLANG=ENG;
/*!=!CHECK_ON
DISP-SIGNL:SYSTEM;
_EOF_STAPEL_RELOAD_
	
	>/var/log/webservice/gendb.out.raw
	popd
	pushd /opt/yaps/script/update_new
	chmod 755 *pl
	./gen_rmx_db.pl $RMXproc -s /tmp/SWU.samtxt 1>>/var/log/webservice/gendb.out.raw 2>&1
	sleep 20
	#OSFOURK-6743 - make sure AMO UPDAT name is restored in all cases
	perl /opt/yaps/script/update_new/gen_rmx_db.pl -a "STA-REN:\":A1H1E:APSN/S/UPDAA\",\":A1H1E:APSN/S/UPDAT\";"
	sleep 20
	perl /opt/yaps/script/update_new/gen_rmx_db.pl -a "RELOVL;"
	popd
	
	rm /dev/.gendb.renameupdat /opt/dscxl/share/stapel
	
	log_gendb "GENDB finished."
	
	grep "H25: NOUN:" /var/log/webservice/gendb.out.raw | grep -v CODEW | grep DELTA && {
		log_gendb "WARNING : GENDB DELTAs found"
		#indicate there were delta-s : use this info later
		grep "H25: NOUN:" /var/log/webservice/gendb.out.raw | grep -v CODEW | grep DELTA | while read aline; do
			log_gendb "$aline"
		done
	}
	
	#download the REGEN protocol files
	log_gendb "Downloading GENDB protocol file from RMX ADS into /var/log/webservice/SEA.samtxt ..."
	sed -i -e "s/put SWU/get SEA/" /opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	sed -i -e "s/226 sam file transfer ok/226/" /opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	pushd /opt/dscxl/share
	/opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	#convert SEA to text
	perl /opt/yaps/script/update_new/sam2text.pl SEA
	mv SEA.TEXT SEA.samtxt
	popd
	cp /opt/dscxl/share/SEA.samtxt /var/log/webservice/
	log_gendb "Downloading GENDB protocol file from RMX SWU into /var/log/webservice/SES.samtxt ..."
	sed -i -e "s/get SEA/get SES/" /opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	sed -i -e "s/226 sam file transfer ok/226/" /opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	pushd /opt/dscxl/share
	/opt/yaps/script/update_new/copy_SAM_to_RMX.exp
	#convert SES to text
	perl /opt/yaps/script/update_new/sam2text.pl SES
	mv SES.TEXT SES.samtxt
	popd
	cp /opt/dscxl/share/SES.samtxt /var/log/webservice/
	
	$REMOTE_STOPPED && {
		log_gendb "Starting back $remoteres ..."
		crm resource start $remoteres
	}
	
	chattr -i /var/opt/webservice/Install.running
	grep "AMO script finished" /var/log/webservice/initADP_RMXdb.log && {
		log_gendb "Removing AMO initialization flag files."
		rm /var/opt/webservice/Install.running
	}
}

[ "$1" = "call_from_init_amo_script" ] && {
	touch /var/opt/webservice/Install.running
	chattr +i /var/opt/webservice/Install.running
	0</dev/null 1>/dev/null 2>/dev/null setsid /bin/bash $0 _in_daemon_ &
	exit 0
}

[ "$1" = "_in_daemon_" ] || exit 1

#from here on we have the daemon part

logger $0 "Started ..."

#make some logging
exec 1>>/var/log/spec_lw_hf.log
exec 2>&1

echo "$0 started at `date`"

PATH_TO_LW_HF=/instmedia/Hotfixes
TEMP_WORK_DIR=`mktemp -d`

#add ASyaps to path
ASYAPS_SCRIPTS_PATH=/opt/yaps/script/common/
export PATH=$PATH:$ASYAPS_SCRIPTS_PATH

#we need to make some changes in the HF  structure: 
#+ remove the readme.txt some not needed directories

echo "Starting preparation ... "
unzip -d  $TEMP_WORK_DIR $PATH_TO_LW_HF/LW*.zip
retcode=$?
if [ $retcode -ne 0 ] ; then
	echo "Error during unzipping of the LW HF with rc $retcode"
	exec_gendb
	chattr -i /var/opt/webservice/Install.running
	grep "AMO script finished" /var/log/webservice/initADP_RMXdb.log && {
		rm /var/opt/webservice/Install.running
	}
	exit 1
fi

mkdir $TEMP_WORK_DIR/:A1H1E:
mv $TEMP_WORK_DIR/OpenScape*/*W*/AP* $TEMP_WORK_DIR/:A1H1E:
rm -fr $TEMP_WORK_DIR/OpenScape*
pushd .
cd $TEMP_WORK_DIR
zip -r Spec_LW.zip .
retcode=$?
if [ $retcode -ne 0 ] ; then
	echo "Error during zipping of the LW HF rc $retcode"
	exec_gendb
	chattr -i /var/opt/webservice/Install.running
	grep "AMO script finished" /var/log/webservice/initADP_RMXdb.log && {
		rm /var/opt/webservice/Install.running
	}
	exit 1
fi
popd

#we apply now (upload content to RMX) the HF
python $ASYAPS_SCRIPTS_PATH/zipdir2rmx.py $TEMP_WORK_DIR/Spec_LW.zip  ### ADD full path
retcode=$?
if [ $retcode -ne 0 ] ; then
	echo "Error during copying the LW HF on the RMX rc $retcode"
	exec_gendb
	chattr -i /var/opt/webservice/Install.running
	grep "AMO script finished" /var/log/webservice/initADP_RMXdb.log && {
		rm /var/opt/webservice/Install.running
	}
	exit 2
fi

#clean up
rm -fr $TEMP_WORK_DIR

#we get now the partnumber of the HF in order to use it RMX
HF_FILE_NAME=`basename $PATH_TO_LW_HF/LW*.zip`

#OSFOURK-24060 V10R1.41 FI with LW-HF does not added the version to rmx APS and LAP2
RMX_BRAND=`echo $HF_FILE_NAME | sed -e s/\.zip// -e s/LW-// | awk -F "_"  '{ print $1" "$2"."$3"."$4 }'`
while [ `echo -en "$RMX_BRAND" | wc -c` -lt 51 ]; do export RMX_BRAND="$RMX_BRAND "; done

#Prepare the stapel file with the L0 brand of the LW HF     ### TO DO - check the BRAND, APS 
BRAND=`(sleep 2 ; echo "root" ; sleep 2 ; echo "hicom" ; sleep 2 ; echo "CHA-FUNCT:SLANG=ENG;" ; sleep 1 ; echo "DISP-APS;" ; sleep 5 ) | telnet 192.0.2.3 | grep -A3 L0-E | grep P30252 | awk '{ print $4 }'`
APS=`(sleep 2 ; echo "root" ; sleep 2 ; echo "hicom" ; sleep 2 ; echo "CHA-FUNCT:SLANG=ENG;" ; sleep 1 ; echo "DISP-APS;" ; sleep 5 ) | telnet 192.0.2.3 | grep L0-E | awk '{ print $4 }'`

#OSFOURK-24060
BRAND=${BRAND%|*}

echo "BRAND=[$BRAND]"
echo "APS=[$APS]"
echo "RMX_BRAND=[$RMX_BRAND"]

( sleep 2 ; echo "root" ; sleep 2 ; echo "hicom" ; sleep 2 ; echo "CHA-FUNCT:SLANG=ENG;" ; sleep 1 ; echo "ADD-ANUM:SP,\"$APS\",\"$BRAND\",\"$RMX_BRAND\";" ; sleep 3 ) | telnet 192.0.2.3

exec_gendb
chattr -i /var/opt/webservice/Install.running
grep "AMO script finished" /var/log/webservice/initADP_RMXdb.log && {
	rm /var/opt/webservice/Install.running
}

echo "$0 ended at `date`"

logger $0 "Done."

exit 0
