#!/bin/sh /etc/rc.common

START=99
STOP=15

. $IPKG_INSTROOT/usr/share/passwall2/utils.sh
APP_FILE=${APP_PATH}/app.sh
LOCK_FILE=${LOCK_PATH}/${CONFIG}.lock

set_lock() {
	mkdir -p "$LOCK_PATH" || return 1
	command exec 9>"$LOCK_FILE" || return 1
	flock -xn 9
}

set_lock_wait() {
	mkdir -p "$LOCK_PATH" || return 1
	command exec 9>"$LOCK_FILE" || return 1
	flock -x 9
}

unset_lock() {
	flock -u 9
	exec 9>&-
}

boot_func() {
	rm -f ${LOCK_PATH}/${CONFIG}_ready.lock
	local delay=$(uci -q get ${CONFIG}.@global_delay[0].start_delay || echo 1)
	if [ "$delay" -gt 0 ]; then
		log_i18n 0 "Start after a delay of %s seconds!" "${delay}"
		sleep $delay
	fi
	restart boot || return 1
	touch ${LOCK_PATH}/${CONFIG}_ready.lock
}

boot() {
	boot_func >/dev/null 2>&1 &
}

start() {
	local action=${2:-$1}
	[ "$action" = "start" ] && action=
	set_lock || { log_i18n 0 "The script is already running, do not run it again. Exit."; return 0; }
	"$APP_FILE" start "$action" 9>&-
	local status=$?
	unset_lock
	return "$status"
}

stop() {
	local action=${2:-$1}
	[ "$action" = "stop" ] && action=
	set_lock_wait || { log_i18n 0 "Unable to acquire the stop lock. Exiting."; return 1; }
	"$APP_FILE" stop "$action" 9>&-
	local status=$?
	unset_lock
	return "$status"
}

restart() {
	local action=${2:-$1}
	[ "$action" = "restart" ] && action=
	set_lock || {
		log_i18n 0 "The script is already running, do not run it again. Exit."
		[ "$action" = "boot" ] && return 1
		return 0
	}
	local update_status=1
	for i in $(seq 1 300); do
		PASSWALL2_UPDATE_LOCK="${LOCK_PATH}/${CONFIG}_sub_rule.lock" lua -e '
			local nixio = require "nixio"
			local file = nixio.open(os.getenv("PASSWALL2_UPDATE_LOCK"), "a")
			if not file then os.exit(2) end
			os.exit(file:lock("tlock") and 0 or 1)
		'
		update_status=$?
		[ "$update_status" -ne 1 ] && break
		sleep 2
	done
	if [ "$update_status" -ne 0 ]; then
		log_i18n 0 "Failed or timed out waiting for subscription/rule updates. Restart cancelled."
		unset_lock
		return 1
	fi
	"$APP_FILE" stop "$action" 9>&-
	"$APP_FILE" start "$action" 9>&-
	local status=$?
	unset_lock
	return "$status"
}

reload() {
	echo "Warning: This service does not support configuration reloading"
	echo "Performing full restart instead..."
	restart
}
