#!/bin/sh

case $(dirname $0) in 
*/node_modules/.bin)
	# launched with yarn $0
	package_dir=$(realpath $(dirname $(realpath $0))/..)
	config_dir=$(pwd)
	;;
*)
	# launched from domoja package
	package_dir=$(dirname $(realpath $0))/..
	config_dir=$package_dir
	;;
esac

case "$npm_execpath" in
 */yarn.*)
	PMGR_RUN=yarn
 	;;
 *)
	PMGR_RUN=npx
	;;
esac

if [ "$(which authbind)" = "" ]
then
	echo 'ERROR: Please install authbind.' >&2
	exit 1
fi

if [ "$(which pm2)" = "" ]
then
	echo 'ERROR: Please install pm2.' >&2
	exit 1
fi

if [ "$1" = "--install" ]
then
	echo pm2 start --interpreter sh $0
	pm2 -s delete `basename $0`
	pm2 -s start --interpreter sh $0
	pm2 -s save
	pm2 list
	exit 0
fi

usage () {
	echo "Usage: `basename $0` [--install | [-h | --help] | [-p | --port <port> ] [-d] [--dev] [<config>]]" >&2
	echo "  --install         : installs domoja with pm2" >&2
	echo "  -h | --help       : this usage help" >&2
	echo "  -p | --port <port>: specify port (443 by default)" >&2
	echo "  -d                : run in debug mode" >&2
	echo "  --dev             : run in dev mode" >&2
	echo "  <config>          : path to config file or directory (./config by default)" >&2
	exit 2 
}

debug=false
devMode=false
while [ "$1" != "" ]
do
case "$1" in
	"--dev")
		$devMode && usage
		devMode=true
		shift
		;;
	"-d")
		$debug && usage
		debug=true
		shift
		;;
	"-p"|"--port")
		[ -z $PORT ] || usage
		shift
		PORT="$1"
		shift
		;;
	"-h"|"--help")
		usage
		shift
		;;
	*)
		[ ! -z $config_path ] && usage
		config_path="$(realpath "$1")"
		shift
		;;
esac
done

[ -z $config_path ] && [ -r "$config_dir/config" ] && config_path="$config_dir/config"
[ -z $config_path ] && echo "Warning: '$config_dir/config' not found, using '$package_dir/config/demo.yml'." && config_path="$package_dir/config/demo.yml"

[ -z $PORT ] && PORT=443

# check that mongodb is running
if [ "`sudo systemctl status mongodb | grep 'active (running)'`" != "" ]
then
    echo MongoDB is running OK.
else
    echo Repairing MongoDB...
    if sudo -u mongodb /usr/bin/mongod --repair --dbpath=/var/lib/mongodb
    then
	echo Restarting MongoDB...
	sudo systemctl force-reload mongodb
	sudo systemctl restart mongodb
    else
	echo 'ERROR: Repair failed. Trying to restart mongodb anyway...'
	sudo systemctl restart mongodb
    fi
fi 2>&1 | sudo tee -a /var/log/domo_app/domo_app.log

set_mixer ()
{
    cardname=$1
    control=$2
    value=$3
    
    # find the card
    c=-1
    ret=0
    res=''
    while [ "$res" = '' -a $ret = 0 ] 
    do
	c=$(expr $c + 1)
	amixer -c $c > /dev/null 2>&1
	ret=$?
	res=`amixer -c $c | grep "'$cardname'"`
    done
    if [ "$res" != '' ]
    then
	# find control
	numid=`amixer -c $c controls | awk -F, "/name='$control'/"' { print $1}'`
	amixer -c $c cset $numid $value
    else
	echo "Card '$cardname' not found." >&2
    fi
}

# set the sound card to 3.5 mm jack
set_mixer 'PCM' 'PCM Playback Route' 1
set_mixer 'PCM' 'PCM Playback Volume' 100%
set_mixer 'PCM' 'PCM Playback Switch' 1

#amixer -c $c cset numid=3 1
#amixer -c $c cset numid=1 400

sudo touch /etc/authbind/byport/443
sudo chmod 777 /etc/authbind/byport/443
sudo touch /etc/authbind/byport/80
sudo chmod 777 /etc/authbind/byport/80

options=
if $devMode
then
	options="$options --dev"
fi

main=$(awk -F\" '$2 == "main" { print $4}' "$package_dir/package.json")

cd $package_dir
if $debug
then
	PORT=$PORT exec authbind --deep nodemon --ext ts --watch . --ignore node_modules,www --exec node --inspect=0.0.0.0 --require ts-node/register $main "$config_path" $options
else
	PORT=$PORT TS_NODE_TRANSPILE_ONLY=true TS_NODE_COMPILER=typescript-cached-transpile exec authbind --deep $PMGR_RUN ts-node $main "$config_path" $options
#	PORT=$PORT TS_NODE_TRANSPILE_ONLY=true TS_NODE_COMPILER=typescript-cached-transpile exec authbind --deep node --require ts-node/register $main "$config_path" $options
fi
