#!/bin/bash


DOUSHIO=/srv
LOG=daemon.log

if [[ "$1" == "start" ]]; then 
	cd $DOUSHIO
	if ps -p $(cat doushio.pid) >/dev/null; then
		echo "[e] daemon already active"
		exit
	fi
	echo "[`date -u +%Y-%m-%dT%T.%3NZ`] starting daemon..." >>$LOG
	node server/server.js 1>/dev/null 2>>$LOG &
	echo $! > doushio.pid
	echo "[+] doushio ($(cat doushio.pid))"
	echo "	doushio $(cat doushio.pid)" >>$LOG
	node archive/daemon.js 1>/dev/null 2>>$LOG &
	echo $! > doushio.archive.pid
	echo "[+] archive ($(cat doushio.archive.pid))"
	echo "	archive $(cat doushio.archive.pid)" >>$LOG
elif [[ "$1" == "stop" ]]; then
	cd $DOUSHIO
	echo "[`date -u +%Y-%m-%dT%T.%3NZ`] stopping daemon..." >>$LOG
	kill $(cat doushio.archive.pid)
	if ps -p $(cat doushio.archive.pid) >/dev/null; then
		echo "[e] failed to stop archive"
		echo "	archive failed" >>$LOG
	else
		echo "[-] archive"
		echo "	archive ok" >>$LOG
	fi
	kill $(cat doushio.pid)
	if ps -p $(cat doushio.pid) >/dev/null; then
		echo "[e] failed to stop doushio"
		echo "	doushio failed" >>$LOG
	else
		echo "[-] doushio"
		echo "	doushio ok">>$LOG
	fi
elif [[ "$1" == "restart" ]]; then
	$0 stop
	$0 start
elif [[ "$1" == "stat" ]]; then
	cd $DOUSHIO
	if ps -p $(cat doushio.pid) $(cat doushio.archive.pid); then 
		echo "ok"
	else	
		echo "server is not up"
	fi
else
	echo "[e] usage: $0 (start|stop|restart|stat)"
fi
