#!/bin/sh

VH_ARCH=$(/bin/uname -m)
if [ -z "${VH_ARCH##*arm*}" ]; then
  VH_ARCH_EXT="arm"
elif [ -z "${VH_ARCH##*x86_64*}" ]; then
  VH_ARCH_EXT="x86_64"
elif [ -z "${VH_ARCH##*aarch64*}" ]; then
  VH_ARCH_EXT="arm64"
else
  VH_ARCH_EXT="i386"
fi

case $1 in
	start)
		echo $(date) "Starting VirtualHere..." >> /var/log/virtualhere.log
		"${SYNOPKG_PKGDEST}"/vhusbd${VH_ARCH_EXT} -b -r /var/log/virtualhere.log -c "${SYNOPKG_PKGDEST}"/config.ini >> /var/log/virtualhere.log 2>&1
		rc=$?
		if [[ $rc -eq 0 ]]; then
			echo $(date) "Started successfully" >> /var/log/virtualhere.log
		else
			echo $(date) "Failed to start" >> /var/log/virtualhere.log
		fi
		exit $rc
	;;
	stop)
		echo $(date) "Stopping VirtualHere..." >> /var/log/virtualhere.log
		killall -q vhusbd${VH_ARCH_EXT}
		sleep 6 # give enough time for vhusbd to shutdowwn
		PID=`pidof vhusbd${VH_ARCH_EXT}`
		if [ -n "$PID" ]; then
			echo $(date) "Problems stopping VirtualHere...now calling kill -9 $PID..." >> /var/log/virtualhere.log
			echo $(date) "If you want to restart VirtualHere you may need to reboot your NAS beforehand" >> /var/log/virtualhere.log
			kill -9 $PID
		fi
		echo $(date) "Stopped successfully" >> /var/log/virtualhere.log
		exit 0
	;;
	status)
		PID=`pidof vhusbd${VH_ARCH_EXT}`
	 	if [ -z "$PID" ]; then
	 		exit 3
	 	else
	 		exit 0
	 	fi
	;;
	log)
		echo "/var/log/virtualhere.log"
		exit 0
	;;
esac
