#! /bin/sh

# PROVIDE: ttrssd
# REQUIRE: LOGIN mysql postgresql
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable `ttrssd':
#
# ttrssd_enable="YES"
#
# ttrssd_local_db (bool):   Set to "YES" by default.
#                           Set it to "NO" if the database is on another
#                           server.

. /etc/rc.subr

name="ttrssd"
rcvar=ttrssd_enable

# read settings, set default values
load_rc_config "${name}"
: ${ttrssd_enable="NO"}
: ${ttrssd_local_db:="YES"}

initdb_php="/usr/local/www/tt-rss/update.php"
required_files="/usr/local/www/tt-rss/config.php"
pidfile="/var/run/${name}.pid"
ppidfile="/var/run/${name}_parent.pid"
phpcli="/usr/local/bin/php"
command_interpreter=$phpcli
long_name="Tiny Tiny RSS updating feeds daemon."
phpupd="/usr/local/www/tt-rss/update_daemon2.php"
ttrssd_log="/var/log/${name}.log"
ttrssd_user="www"

start_precmd=${name}_prestart
start_cmd=${name}_start
stop_cmd=${name}_stop

CHECK_CMD="/usr/local/bin/mysqladmin -u mysqld ping"
CHECK_MSG="${name}: mysqladmin command failed; mysql not ready?"
#CHECK_CMD="/usr/local/bin/pg_isready"
#CHECK_MSG="${name}: postgresql status failed; postgresql not ready?"

ttrssd_start() {
	if ! [ -x $phpcli ]; then
		echo "$phpcli not found"
		exit 1
	fi

	if [ -f $pidfile ]; then
		echo "$name already running?"
		exit 2
	fi

	echo "Starting $long_name"
	daemon -H -P "$ppidfile" -p "$pidfile" \
		  -u "$ttrssd_user" -o "$ttrssd_log" \
		sh -c "${initdb_php} --update-schema=force-yes; $phpupd"
}

ttrssd_stop() {
	if ! [ -f $pidfile ]; then
		echo "$name not running?"
		exit 1
	fi

	echo "Stopping $long_name"
	pkill -CHLD -F "$pidfile"
	pkill -F "$pidfile"
	pwait "$(cat $ppidfile)"
}

ttrssd_prestart() {
	if checkyesno ttrssd_local_db; then
		# Wait for the local database to be started

		for n in $(seq 1 10); do
			if $CHECK_CMD > /dev/null 2>&1; then
			    return
			fi
			sleep 1
		done
		err 1 $CHECK_MSG
	fi
}

run_rc_command "$1"
