#! /bin/sh

if [ "${XDG_CURRENT_DESKTOP}" = "Deepin" ]; then
	UI_PID_PATH="$XDG_DATA_HOME/.SynologyDrive/ui.pid"
	APP_PATH="$XDG_DATA_HOME/.SynologyDrive/SynologyDrive.app"
else
	UI_PID_PATH="$HOME/.SynologyDrive/ui.pid"
	APP_PATH="$HOME/.SynologyDrive/SynologyDrive.app"
fi
UI_PATH="$APP_PATH/bin/cloud-drive-ui"

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


stop(){

	if [ ! -f ${UI_PID_PATH} ]; then
		#not running
		return 0
	fi

	UI_PID=`grep pid ${UI_PID_PATH} | sed 's/pid=//g' | sed 's/"//g'`

	kill $UI_PID
	while [ 1 ] ; do
		check_process
		if [ $? -eq 0 ];
		then
			# already stop
			break;
		fi
		sleep 1
	done



}

start(){

	env LD_LIBRARY_PATH="$APP_PATH/lib" QT_QPA_PLATFORMTHEME=gnome QT_QPA_FONTDIR=/usr/share/fonts/truetype QT_PLUGIN_PATH="$APP_PATH/lib/plugins" $UI_PATH &

}

autostart(){

	#wait for gnome-shell ready
	sleep 10
	env LD_LIBRARY_PATH="$APP_PATH/lib" QT_QPA_PLATFORMTHEME=gnome QT_QPA_FONTDIR=/usr/share/fonts/truetype QT_PLUGIN_PATH="$APP_PATH/lib/plugins" $UI_PATH &
}

case $1 in

	stop)
		stop
		exit $?
	;;
	start)
		start
		exit $?
	;;
	autostart)
		autostart
		exit $?
	;;
esac
