#!/bin/bash

# This script checks if deCONZ is running and the REST-API is reachable at configured port.
# To activate copy this file to /etc/watchdog.d/

# uptime in seconds
UP=$(cat /proc/uptime | cut -f1 -d'.')

# this test shall trigger only after 3 minutes bootup
if [ $UP -le 180 ]; then
	exit 0
fi

PIDFILE=`find /var/run/user -name deconz.pid 2>/dev/null`

if [ -n "$PIDFILE" ]; then
	pid=`cat $PIDFILE`
	rundir=`dirname $PIDFILE`

	# check if process exists
	kill -0 $pid
	if [ $? -eq 0 ]; then
		# check if web server is reachable
		port=`cat ${rundir}/data/config.ini | grep -e '^port=' | cut -f2 -d'='`
		if [ -n "$port" ]; then
			curl --head "127.0.0.1:${port}" > /dev/null 2>&1 || exit 1
#			echo "deCONZ PID $pid running at port $port"
		fi
	else
#		echo "deCONZ with PID $pid not running"
		rm -f $PIDFILE
		exit 1
	fi
fi

exit 0
