#!/bin/bash
############################################
# synctime
#
# Helper script to change the synchrtime parameter in the registry
# Usage: ./syctime <hh:mm>
# 
# Copyright (c) 2016 Unify GmbH & Co. KG
# Demeter Aron, Kemenes Robert 
# aron.demeter.ext@unify.com, robert.kemenes.ext@unify.com
#
# Last modification: 06.04.2017 in dtb-1.0-28.noarch.rpm
############################################

# 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

# Evaluate parameters: if the number of parameters is less than 1, or it is not the standard than print out the help.
if [ $# -lt 1 ]; then
    logger -t $CMD -p INFO -s "Usage: $0 <hh:mm>."
    exit
fi;

# If the parameter contains the ":" delimiter then split into hh:mm and verify the ranges
echo "$1" | grep ":" >/dev/null 2>&1   
if [ "$?" -eq "0" ]; then
  hh=${1%:*}; 		#hour part
  mm=${1#*:}; 		#minute part
  if [ ${#hh} -ne 2 ] || [ ${#mm} -ne 2 ]; then
     plog "ERROR: Length must be 2:2"
	 exit
  else
    rhh='^0[0-9]|1[0-9]|2[0-3]+$'						#hour range and format
    rmm='^0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]+$'	#minute range and format
    if ! [[ $hh =~ $rhh ]] || ! [[ $mm =~ $rmm ]]; then
	  echo "ERROR: Wrong range format"
	  exit
    fi
  fi
else
  plog "Usage: $0 <hh:mm>."
  exit
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 SynchrTime /t REG_SZ /d $* /f 1>/dev/null 2>/dev/null

plog "The new synchronization parameter was cahnged in Registry to '$1'."

# 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 to '$1'."
