#!/bin/sh

if [ "${XDG_CURRENT_DESKTOP}" = "Deepin" ]; then
	INSTALL_PATH="/opt/apps/com.synology.drive/files/Synology/SynologyDrive"
else
	INSTALL_PATH="/opt/Synology/SynologyDrive"
fi
LIB_PATH="$INSTALL_PATH/lib"
BIN_PATH="$INSTALL_PATH/bin/launcher"

check_process()
{
	pid=$1
	kill -0 $pid > /dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 1
	else
		return 0
	fi
}

stop_process()
{
	counter=0
	pid=$1
	kill $pid


	while [ 1 ] ; do
		check_process $pid

		if [ $? -eq 0 ]; then
			# already stop
			break;
		fi

		if [ $counter -eq 10 ]; then
			# force kill
			kill -9 $pid
			break;
		fi

		sleep 1
		counter=$((counter+1))
	done
}

gracefull_stop_service()
{
if [ "${XDG_CURRENT_DESKTOP}" = "Deepin" ]; then
	app_path="$XDG_DATA_HOME/.SynologyDrive"
else
	user_name=$1
	home_path=`eval echo ~"$user_name"`
	app_path="$home_path/.SynologyDrive"
fi
	pid_file="$app_path/ui.pid"

	if [ ! -f "$pid_file" ]; then
		#not running
        return 0
	fi

	pid=`grep pid "$pid_file" | sed 's/pid=//g' | sed 's/"//g'`
	stop_process $pid
}

start()
{
	env "LD_LIBRARY_PATH=$LIB_PATH"  QT_QPA_PLATFORMTHEME=gnome "$BIN_PATH" &
}

stop()
{
	gracefull_stop_service $USER
}

restart()
{
	stop
	start
}

autostart()
{
	sleep 10
	start
}

case $1 in
	start)
		start
		exit $?
	;;
	autostart)
		autostart
		exit $?
	;;
	stop)
		stop
		exit $?
	;;
	restart)
		restart
		exit $?
	;;
	*)
		start
		exit $?
	;;
esac
