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

START=99
STOP=15

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

set_lock() {
	[ ! -d "$LOCK_FILE_DIR" ] && mkdir -p $LOCK_FILE_DIR
	exec 999>"$LOCK_FILE"
	flock -xn 999
}

unset_lock() {
	flock -u 999
	rm -rf "$LOCK_FILE"
}

unlock() {
	failcount=1
	while [ "$failcount" -le 10 ]; do
		if [ -f "$LOCK_FILE" ]; then
			let "failcount++"
			sleep 1s
			[ "$failcount" -ge 10 ] && unset_lock
		else
			break
		fi
	done
}

boot_func() {
	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
	touch ${LOCK_FILE_DIR}/${CONFIG}_ready.lock
}

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

start() {
	set_lock
	[ $? == 1 ] && log_i18n 0 "The script is already running, do not run it again. Exit." && exit 0
	$APP_FILE start
	unset_lock
}

stop() {
	unlock
	set_lock
	[ $? == 1 ] && log_i18n 0 "Stop the script and wait for a timeout, then exit without repeating the process." && exit 0
	$APP_FILE stop
	unset_lock
}

restart() {
	set_lock
	[ $? == 1 ] && log_i18n 0 "The script is already running, do not run it again. Exit." && exit 0
	$APP_FILE stop
	$APP_FILE start
	unset_lock
}

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