#!/bin/bash
############################################
# dtb-wrapper
#
# Wrapper script for starting and stopping DTB Master/Server under wine.
# Usage: ./dtb-wrapper DTBMaster|DTBServer start|stop|status
#
# Copyright (c) 2016 Unify GmbH & Co. KG
# Demeter Aron, Kemenes Robert 
# aron.demeter@atos.net, robert.kemenes.@atos.net
#
# Last modification: 06.06.2018 in dtb-1.0-38.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 parameter is less than 2, or it is not the standard than print out the help.
if [ $# -ne 2 ] || \
  ([ $1 != "DTBMaster" ] && [ $1 != "DTBServer" ]) || \
  ([ $2 != "start" ] && [ $2 != "stop" ] && [ $2 != "status" ])
then
    logger -t $CMD -p ERROR -s "Usage: $0 DTBMaster|DTBServer start|stop|status"
    exit
fi;

if [ $1 == "DTBMaster" ]; then
	EXE="$DTB_MASTER_EXE"
	SHUTDOWNEXE="$DTBMASTER_SHUTDOWN"
else
    EXE="$DTB_SERVER_EXE"
	SHUTDOWNEXE="$DTBSERVER_SHUTDOWN"
fi

# Get the current status
checkproc "$EXE"
status=$?

# In status mode we return the result and exit
if [ $2 == "status" ]
then
    if [ $status == 0 ]
    then
		echo "Status: $1 is running."
        exit 0
    else
		echo "Status: $1 is not running."
        exit 2
    fi
fi

# The status is checked every time, so don't fulfill the logs.

# Is the desired operation really necessary?
if [ $2 == "start" ] && [ $status -eq 0 ]
then
	plog "Trying to start $1, but it is already running; Nothing to do."
    exit 0
elif [ $2 == "stop" ] && [ $status -ne 0 ]
then
    plog "Trying to stop $1, but it is not running; Nothing to do."
    exit 0
fi

# If the desired operation is ready to go
plog "Trying to $2 $1..."

if [ $2 == "start" ]; then

	# 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


	# ensure that the working directory has the right ownership
	if [ $(stat -c '%U' ${DTB_DRBD_SHARE}/$1) != ${DTB_USER} ]; then
		plog "Changing the ownership of working directory ${DTB_DRBD_SHARE}/$1 to ${DTB_USER}:${DTB_GROUP}."
        chown -R $DTB_USER:$DTB_GROUP ${DTB_DRBD_SHARE}/$1
	fi

	# copy the appropriate ini file to the working directory
	sudo -u $DTB_USER cp $DTB_DRBD_SHARE/$1/config/*.ini $DTB_WORKINGDIR/drive_c/$1
	
	# empty the export and import directory
	plog "Clearing the import and export directories."
	sudo -u $DTB_USER rm -r $DTB_DRBD_SHARE/DTBServer/export/*
	sudo -u $DTB_USER rm -r $DTB_DRBD_SHARE/DTBServer/import/*

    # go into working directory
    cd $DTB_WORKINGDIR/drive_c/$1

	# start via wine
	plog "Trying to start ${EXE} using wine."
	sudo -u $DTB_USER WINEDEBUG=fixme-all,err-ole,-rpc \
					  WINEARCH=win32 \
					  WINEPREFIX=$DTB_WORKINGDIR \
					  DISPLAY=:$XDISPLAYNR.0 \
					  $WINE_BIN $EXE &
	sleep 1
	
	# test, if the process has been started
	checkproc "$EXE"
	if [ $? != 0 ]; then
		plog "$1 could not be started."
	else
	    plog "$1 started."
	fi

else

	# try a graceful shutdown
	plog "Trying to graceful shutdown ${EXE}."
	sudo -u $DTB_USER WINEDEBUG=fixme-all,err-ole,-rpc \
					  WINEARCH=win32 \
					  WINEPREFIX=$DTB_WORKINGDIR \
					  DISPLAY=:$XDISPLAYNR.0 \
					  $WINE_BIN $SHUTDOWNEXE
	sleep 1
	
	# test, if gracefull shutdown was successful
	checkproc "$EXE"
	if [ $? == 0 ]; then
		# kill wine process
		plog "Graceful shutdown is not working; Trying to kill ${EXE}."
		# ps -ef | grep $EXE | awk '{print $2}' | xargs kill
		for pid in $(ps -ef | grep $EXE | awk '{print $2}'); do kill $pid; done
	else
	    plog "$1 stopped."
	fi
fi
