#!/bin/bash
############################################
# dtb-manager
#
# Helper script to change the IP, user and password parameter in the registry
# Usage: ./dtb-manager
#
# rpm71 - using DTBconfigFile.xml
############################################

# 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

IP=$(readConfigXML "manager-ip")
usr=$(readConfigXML "manager-user")
pwd=$(readConfigXML "manager-password")
pwd=$(echo $pwd | openssl aes-256-cbc -a -d -salt -k '1825e09252d7c6f66f5e1be666154306')

# 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!"
		exit 1;
	elif [ `echo $IP | tr '.' ' ' | wc -w` -ne 4 ]; then
		plog "ERROR: Exiting with: 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!"
						exit 1;
				elif [[ $OCTET -lt 0 || $OCTET -gt 255 ]]; then
						plog "ERROR: Exiting with: Invalid IP: an octet in not in range 0-255!"
						exit 1;
				fi
		done
	fi

# ensure, Xvnc server and lwm are running
checkproc "$XVNC_BIN"
if [ $? != 0 ]; then
	plog "$XVNC_BIN is not running." 
	$XSERVER_START
	if [ $? != 0 ]; then
		plog "ERROR: Xvnc server/lwm not ready; Exiting."
		exit 1
	fi
fi

# Finally try to call the registry command to set the synchronization time
sudo -u $DTB_USER WINEDEBUG=fixme-all,err-ole,-rpc \
                  WINEARCH=win32 \
                  WINEPREFIX=$DTB_WORKINGDIR \
                  DISPLAY=:$XDISPLAYNR.0 \
                  $WINE_BIN reg add HKLM\\Software\\Siemens\\DTBNetzConfig\\HDMS\\ /v HDMSIPAddress /t REG_SZ /d $IP /f 1>/dev/null 2>/dev/null

sudo -u $DTB_USER WINEDEBUG=fixme-all,err-ole,-rpc \
                  WINEARCH=win32 \
                  WINEPREFIX=$DTB_WORKINGDIR \
                  DISPLAY=:$XDISPLAYNR.0 \
                  $WINE_BIN reg add HKLM\\Software\\Siemens\\DTBNetzConfig\\HDMS\\ /v HDMSLogin /t REG_SZ /d $usr /f 1>/dev/null 2>/dev/null
				  
sudo -u $DTB_USER WINEDEBUG=fixme-all,err-ole,-rpc \
                  WINEARCH=win32 \
                  WINEPREFIX=$DTB_WORKINGDIR \
                  DISPLAY=:$XDISPLAYNR.0 \
                  $WINE_BIN reg add HKLM\\Software\\Siemens\\DTBNetzConfig\\HDMS\\ /v HDMSPasswd /t REG_SZ /d $pwd /f 1>/dev/null 2>/dev/null
				  
plog "The new synchronization parameter was changed in Registry to IP=$IP, Usr=$usr, Pwd=*****.";

# Now we can force the DTB to get the sync time from the registry.
echo "11" > $DTB_DRBD_SHARE/DTBMaster/winedir/SyncTrig.cfg;

plog "The new synchronization parameter was changed in DTB too."