#!/bin/sh
# Copyright 2026 51DDNS
# SPDX-License-Identifier: Apache-2.0
set -eu

dir=/var/run/51ddns-router-credential
proof="$dir/ready"
umask 022
sample=
trap 'rm -f "$proof" "${sample:-$proof}"; exit 0' INT TERM
verified_hash=

native_password_configured() {
	[ "$(uci -q get 'rpcd.@login[0].username')" = root ] &&
		[ "$(uci -q get 'rpcd.@login[0].password')" = '$p$root' ] &&
		! uci -q get 'rpcd.@login[1]' > /dev/null || return 1
	hash="$(awk -F: '$1 == "root" && $2 ~ /^\$[[:alnum:]]+\$/ && length($2) >= 25 { print $2 }' /etc/shadow)"
	[ -n "$hash" ] || return 1
	[ "$hash" != "$verified_hash" ] || return 0
	if reply="$(ubus -S -t 2 call session login '{"username":"root","password":""}' 2>/dev/null)"; then
		sid="$(printf '%s\n' "$reply" | jsonfilter -e '@.ubus_rpc_session')"
		case "$sid" in
			''|*[!0-9a-f]*) ;;
			*) [ "${#sid}" -ne 32 ] || ubus -t 2 call session destroy "{\"ubus_rpc_session\":\"$sid\"}" >/dev/null 2>&1 || : ;;
		esac
		return 1
	else
		# UBUS_STATUS_PERMISSION_DENIED. A timeout or missing rpcd is not proof.
		[ "$?" = 6 ] || return 1
	fi
	verified_hash="$hash"
}

while [ "$(uci -q get 51ddns.main.router_web)" = 1 ] &&
	[ -n "$(uci -q get 51ddns.main.router_web_direct_hostname)" ]; do
	[ ! -L "$dir" ] || exit 1
	if [ -d "$dir" ]; then
		sample="$(mktemp "$dir/.check.XXXXXX")"
		if native_password_configured; then
			chmod 0644 "$sample"
			mv -f "$sample" "$proof"
		else
			rm -f "$sample" "$proof"
		fi
		sample=
	fi
	sleep 5
done
rm -f "$proof"
