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

START=99
STOP=15

ROOT="${IPKG_INSTROOT:-}"
. "$ROOT/usr/share/passwall/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
		echolog "执行启动延时 $delay 秒后再启动!"
		sleep $delay
	fi
	restart boot || return 1
	touch ${LOCK_PATH}/${CONFIG}_ready.lock
}

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

start() {
	set_lock || { echolog "脚本已经在运行，不重复运行，退出."; return 0; }
	"$APP_FILE" start "$2" 9>&-
	unset_lock
}

stop() {
	set_lock_wait || { echolog "无法取得停止锁，退出."; return 1; }
	"$APP_FILE" stop "$2" 9>&-
	unset_lock
}

restart() {
	local action=${2:-$1}
	[ "$action" = "restart" ] && action=
	set_lock || { echolog "脚本已经在运行，不重复运行，退出."; return 0; }
	local update_status=1
	for i in $(seq 1 300); do
		PASSWALL_UPDATE_LOCK="${LOCK_PATH}/${CONFIG}_sub_rule.lock" lua -e '
			local nixio = require "nixio"
			local file = nixio.open(os.getenv("PASSWALL_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
		echolog "等待订阅/规则更新结束失败或超时，取消重启."
		unset_lock
		return 1
	fi
	"$APP_FILE" stop "$action" 9>&-
	"$APP_FILE" start "$action" 9>&-
	unset_lock
}

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