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

lock_file="/tmp/lock/wdoc-singbox.lock"

if [ -e "$lock_file" ]; then
	old_pid=$(cat "$lock_file" 2>/dev/null)
	if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then
		exit 0
	fi
fi

echo "$$" > "$lock_file"
trap 'rm -f "$lock_file"' EXIT INT TERM

config_load wdoc-singbox
config_get LOG  main log 1
config_get FAKEIP_RANGE_UCI  main fakeip_range
config_get URLTEST  main url_test

[ -z "$URLTEST" ] && exit 0

CONFIG=$(uci -q get sing-box.main.conffile)

log_wdoc_singbox() {
	[ "$LOG" != "1" ] && return 0
	local TEXT="$1"
	[ -n "$TEXT" ] && logger -p daemon.info -t wdoc_singbox "$TEXT"
}

if [ -z "$FAKEIP_RANGE_UCI" ]; then
	FAKEIP_RANGE=$(grep inet4_range "$CONFIG" | awk -F'"' '{print $4}')
	if [ -z "$FAKEIP_RANGE" ]; then
		log_wdoc_singbox "FakeIP range not found in config"
		exit 0
	fi
else
	FAKEIP_RANGE="$FAKEIP_RANGE_UCI"
fi

FAKEIP_PREFIX="$FAKEIP_RANGE"

FAKEIP_OCT1=$(echo "$FAKEIP_RANGE" | awk -F. '{print $1}')
FAKEIP_OCT2=$(echo "$FAKEIP_RANGE" | awk -F. '{print $2}')

check_fakeip() {
	addresses=$(nslookup "$URLTEST" 127.0.0.1 2>/dev/null | awk '/^Name:/{f=1} f && /Address: /{print $2}')
	for ip in $addresses; do
		[ "$ip" = "::" ] && continue
		o1=$(echo "$ip" | awk -F. '{print $1}')
		o2=$(echo "$ip" | awk -F. '{print $2}')
		if [ "$o1" -eq "$FAKEIP_OCT1" ] && { [ "$o2" -eq "$FAKEIP_OCT2" ] || [ "$o2" -eq $((FAKEIP_OCT2+1)) ]; }; then
			return 0
		fi
	done
	return 1
}

if check_fakeip; then
	log_wdoc_singbox "FakeIP DNS: OK"
	log_wdoc_singbox "Sing-box: OK"
	exit 0
fi

log_wdoc_singbox "FakeIP DNS NOT working"

status=$(/etc/init.d/sing-box status 2>/dev/null)
if [ "$status" != "running" ]; then
	log_wdoc_singbox "sing-box service not running!"
	log_wdoc_singbox "sing-box check config..."
	if ! sing-box check -c "$CONFIG" >/dev/null 2>&1; then
		log_wdoc_singbox "Check sing-box config: problems detected"
		exit 0
	fi
	log_wdoc_singbox "Check sing-box config - OK"
	log_wdoc_singbox "Starting sing-box..."
	/etc/init.d/sing-box start
else
	log_wdoc_singbox "Sing-box running, checking config..."
	if ! sing-box check -c "$CONFIG" >/dev/null 2>&1; then
		log_wdoc_singbox "Check sing-box config: problems detected, cannot restart"
		exit 0
	fi
	log_wdoc_singbox "Config valid, trying restarting sing-box..."
	/etc/init.d/sing-box restart
fi

sleep 1
if check_fakeip; then
	log_wdoc_singbox "Sing-box OK after restart!"
else
	log_wdoc_singbox "FakeIP DNS: still NOT working. Please check the sing-box configuration manually"
fi

exit 0
