#!/bin/sh
# SPDX-License-Identifier: Apache-2.0
# Copyright ForestVPN
#
# ForestVPN's pages on a legacy (Lua-only) LuCI: 18.06 and the vendor forks on it (photonicatWrt, Lean's LEDE), which never read
# /usr/share/luci/menu.d. Such a LuCI gets three copies from /usr/share/forestvpn/luci-legacy (a controller, a template, legacy.js); a modern
# LuCI gets nothing. Copies, not links: uhttpd does not serve a file whose real path is outside /www.
#   luci-legacy detect   exit 0 on a legacy LuCI the pages can run on (it has uhttpd's /ubus), 1 otherwise
#   luci-legacy link     uci-defaults/90-forestvpn: on such a LuCI, the three copies and the `ifname` alias of network.forestvpn (its
#                        interface model reads only `ifname`: without it Network > Interfaces says "Unsupported protocol type"; a
#                        modern LuCI would prompt a migration for it). Uncommitted: 90-forestvpn commits. Elsewhere it is `unlink`.
#   luci-legacy unlink   prerm: the three copies go
# FVPN_ROOT=<dir> runs against a fake root (testing/openwrt/luci/legacy_sh_test.sh).
# The one-tap update runs this under rpcd's umask 077: uhttpd serves the copies as plain files, so 0600 ones answer 403 and every page is empty.
umask 022
R=${FVPN_ROOT:-}
S=$R/usr/share/forestvpn/luci-legacy
CTL=$R/usr/lib/lua/luci/controller/forestvpn.lua
VIEW=$R/usr/lib/lua/luci/view/forestvpn
JS=$R/www/luci-static/resources/forestvpn/legacy.js
DSP=$R/usr/lib/lua/luci/dispatcher.lua

detect() {
	[ -f "$DSP" ] || return 1
	[ -e "$R/usr/share/ucode/luci/dispatcher.uc" ] && return 1
	grep -q 'menu\.d' "$DSP" && return 1
	grep -Eq '^[[:space:]]*option[[:space:]]+ubus_prefix[[:space:]]' "$R/etc/config/uhttpd" 2>/dev/null
}
# LuCI's caches: 18.06's index cache is one file with no suffix, later ones carry a suffix
caches() { rm -rf "$R/tmp/luci-indexcache" "$R"/tmp/luci-indexcache.* "$R/tmp/luci-modulecache"; }
unlink_all() { rm -f "$CTL" "$VIEW/page.htm" "$JS"; rmdir "$VIEW" 2>/dev/null; caches; }

case "$1" in
detect) detect; exit $? ;;
link)
	if detect; then
		mkdir -p "${CTL%/*}" "$VIEW" "${JS%/*}"
		cp "$S/controller.lua" "$CTL" && cp "$S/page.htm" "$VIEW/page.htm" && cp "$S/legacy.js" "$JS" &&
			chmod 0644 "$CTL" "$VIEW/page.htm" "$JS" # cp over an existing file keeps its mode: this heals a router the update already broke
		case " $(uci -q get forestvpn.main.added) " in
		*" network "*) [ -n "$(uci -q get network.forestvpn.ifname)" ] || uci -q set network.forestvpn.ifname=fvpn0 ;;
		esac
		caches
	else
		unlink_all
	fi ;;
unlink) unlink_all ;;
*) echo "usage: luci-legacy detect|link|unlink" >&2; exit 2 ;;
esac
exit 0
