#!/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() {
	[ ! -d "$LOCK_PATH" ] && mkdir -p $LOCK_PATH
	exec 999>"$LOCK_FILE"
	flock -xn 999
}

set_lock_wait() {
	[ ! -d "$LOCK_PATH" ] && mkdir -p "$LOCK_PATH"
	exec 999>"$LOCK_FILE"
	flock -x 999
}

unset_lock() {
	flock -u 999
}

boot_func() {
	rm -f ${LOCK_PATH}/${CONFIG}_ready.lock
	rm -f ${LOCK_PATH}/${CONFIG}_rule_update.lock
	rm -f ${LOCK_PATH}/${CONFIG}_subscribe.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
	touch ${LOCK_PATH}/${CONFIG}_ready.lock
}

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

start() {
	set_lock
	[ $? == 1 ] && echolog "脚本已经在运行，不重复运行，退出." && exit 0
	$APP_FILE start $2
	unset_lock
}

stop() {
	set_lock_wait
	[ $? != 0 ] && echolog "无法取得停止锁，退出." && exit 1
	$APP_FILE stop $2
	unset_lock
}

restart() {
	local action=${2:-$1}
	[ "$action" = "restart" ] && action=
	set_lock
	[ $? == 1 ] && echolog "脚本已经在运行，不重复运行，退出." && exit 0
	rule_lock=${LOCK_PATH}/${CONFIG}_rule_update.lock
	sub_lock=${LOCK_PATH}/${CONFIG}_subscribe.lock
	for i in $(seq 1 300); do
		if [ ! -f "$rule_lock" ] && [ ! -f "$sub_lock" ]; then
			break
		fi
		sleep 2
	done
	rm -f "$rule_lock" "$sub_lock"
	$APP_FILE stop $action
	$APP_FILE start $action
	unset_lock
}

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