#!/bin/sh -x
#

ARCH=$(cat /etc/.arch)

PYBIN=python3

if [ "$ARCH" == sh4 ];then
	PYBIN=python
fi

if [ "$1" == "remove" ];then
	opkg remove ${PYBIN}-flask --force-removal-of-dependent-packages
	exit
fi

if [ "$1" == "install" ];then
	opkg update > /dev/null 2>&1
	check1=`opkg list_installed ${PYBIN}-requests | wc -l`
	check2=`opkg list_installed ${PYBIN}-flask | wc -l`
	if [ "$check1" == 0 ] || [ "$check2" == 0 ];then
		opkg install ${PYBIN} ${PYBIN}-trio ${PYBIN}-xmlrpc ${PYBIN}-isodate ${PYBIN}-pycountry ${PYBIN}-pycryptodomex
		opkg install ${PYBIN}-requests ${PYBIN}-flask
	fi
	exit
fi


if [ -e /mnt/swapextensions/usr/local/share/titan/plugins/network/vavoo/start.sh ];then
	INSTDIR=/mnt/swapextensions/usr/local/share/titan/plugins/network/vavoo
elif [ -e /mnt/swapextensions/usr/local/share/titan/plugins/network/vavoo/start.sh ];then
	INSTDIR=/var/swap/usr/local/share/titan/plugins/network/vavoo
elif [ -e /var/usr/local/share/titan/plugins/network/vavoo/start.sh ];then
	INSTDIR=/var/usr/local/share/titan/plugins/network/vavoo
fi

if [ -z "$INSTDIR" ];then
	echo [$0] skip start.sh is not installed
else
	if [ "$1" == "start" ];then
		opkg update
		check1=`opkg list_installed ${PYBIN}-requests | wc -l`
		check2=`opkg list_installed ${PYBIN}-flask | wc -l`
		if [ "$check1" == 0 ] || [ "$check2" == 0 ];then
			opkg install ${PYBIN} ${PYBIN}-trio ${PYBIN}-xmlrpc ${PYBIN}-isodate ${PYBIN}-pycountry ${PYBIN}-pycryptodomex
			opkg install ${PYBIN}-requests ${PYBIN}-flask
		fi

		echo [$0] ntpdate start
		ntpdate -b ptbtime1.ptb.de
		echo [$0] vavoo start
		$INSTDIR/start.sh start
	fi

	if [ "$1" == "stop" ];then
		echo [$0] vavoo stop
		$INSTDIR/start.sh stop
	fi

	if [ "$1" == "restart" ];then
		echo [$0] vavoo restart
		$INSTDIR/start.sh restart
	fi

	if [ "$1" == "status" ];then
		echo [$0] vavoo status
		$INSTDIR/start.sh status
	fi
fi
