#!/bin/sh
[ -n "${IPKG_INSTROOT}" ] && exit 0

WEBUSER=uhttpd
id "$WEBUSER" >/dev/null 2>&1 || WEBUSER=root
mkdir -p /etc/ipman
if [ ! -f /etc/ipman/settings ]; then
	for k in iface username password http_port allow_nonlan; do
		v="$(uci -q get "ipman.settings.$k")"
		[ -n "$v" ] && echo "$k=$v" >> /etc/ipman/settings
	done
fi
touch /etc/ipman/settings
# The camera password is in here, so keep it off limits to everyone else.
chown -R "$WEBUSER" /etc/ipman 2>/dev/null
chmod 0700 /etc/ipman
chmod 0600 /etc/ipman/settings

# The store now holds the credentials, so drop the copy in UCI: that one is
# picked up by RutOS configuration backups, and a camera password does not
# belong in every backup archive.
uci -q delete ipman.settings.password && uci commit ipman

# rpcd keeps serving the ACL set it read at boot, so without this a newly
# installed scope is never granted and every API call returns Unauthorized —
# with nothing in any log to explain it.
[ -x /etc/init.d/rpcd ] && ubus call session reload_acls 2>/dev/null

# A full restart, not a HUP.  On RutOS 7.22 a HUP does not make uhttpd re-read
# the API route table, so every endpoint answers "Endpoint not implemented"
# until something restarts it — which looks exactly like a broken package.
/etc/init.d/uhttpd restart >/dev/null 2>&1 || killall -q -1 uhttpd 2>/dev/null

# Tell the web UI to re-read its menu, so the new page appears without the
# operator having to reload or log out.
ubus send vuci.notify '{"event": "reload_routes"}' 2>/dev/null
exit 0
