#!/bin/sh
# Enable for boot + create the default UCI config (skip when building an image
# offline). `start` only when a migrated config is already enabled (a fresh
# install refuses to run until configured, and opkg may run this under `set -e`).
# Every command is guarded so it can't abort
# the install. The UCI config is written here (not shipped in the package) because
# RUTOS opkg installs package files under an offset root (/usr/local), which is
# wrong for /etc/config and trips the conffiles mechanism.
#
# This postinst also migrates a device from the old "netbird" package in place:
# the old service is stopped, the peer identity (/etc/netbird/config.json — its
# private_key IS the peer on the controller, so it is MOVED, never regenerated)
# and the old UCI settings are carried over, then the new service is enabled.
[ -n "${IPKG_INSTROOT}" ] || {
    # --- netbird → qetra migration -----------------------------------------
    # 1) Old service out of the way (may not exist; every step best-effort).
    [ -x /etc/init.d/netbird ] && {
        /etc/init.d/netbird stop 2>/dev/null || true
        /etc/init.d/netbird disable 2>/dev/null || true
    }

    # 2) Peer identity: MOVE (not copy) so exactly one copy of the private key
    #    exists; never overwrite an already-present qetra identity.
    if [ -f /etc/netbird/config.json ] && [ ! -f /etc/qetra/config.json ]; then
        mkdir -p /etc/qetra 2>/dev/null || true
        mv /etc/netbird/config.json /etc/qetra/config.json 2>/dev/null || true
    fi

    # 3) UCI settings: the option names are unchanged, only the section type is,
    #    so the old file converts with a one-line sed. The original is kept as
    #    /etc/config/netbird.migrated for rollback (and so the old namespace
    #    stops resolving). Never clobber an existing qetra config.
    if [ ! -f /etc/config/qetra ] && [ -f /etc/config/netbird ]; then
        sed 's/^config[[:space:]]\{1,\}netbird/config qetra/' \
            /etc/config/netbird > /etc/config/qetra 2>/dev/null || true
        mv /etc/config/netbird /etc/config/netbird.migrated 2>/dev/null || true
    fi
    # -----------------------------------------------------------------------

    /etc/init.d/qetra enable 2>/dev/null || true

    # Write UCI defaults only if absent, so upgrades keep the user's settings.
    if [ ! -f /etc/config/qetra ]; then
        cat > /etc/config/qetra <<'UCI_EOF'
# Qetra Rust client — UCI config (/etc/config/qetra).
# Edit here (or via LuCI / the RUTOS web page), then: /etc/init.d/qetra restart
#
# The persistent WireGuard key lives in /etc/qetra/config.json (auto-created on
# first start). The setup key below is only needed for the FIRST registration;
# afterwards this peer re-authenticates by its wg pubkey with no key.

config qetra 'main'
	# Master switch. Set to 1 to run the service.
	option enabled '0'
	# Management server URL, e.g. https://access.stratus.tr:443
	option management_url ''
	# One-time setup key from the Qetra dashboard (first registration only).
	option setup_key ''
	# Hostname to register with (blank = system hostname).
	option hostname ''
	# Log verbosity: error | warn | info | debug | trace
	option log_level 'info'
	# Enforce the inbound ACL (default off; fragile on OpenWrt's iptables-nft).
	option acl '0'
	# Lazy relay connections (default off; for very large networks).
	option lazy '0'
	# ICE-lite direct P2P (default off; relay stays the fallback).
	option ice '0'

	# --- RUTOS standalone web UI (served by the daemon on a separate port) ---
	# Enable the built-in config/status page (OpenWrt users can use LuCI instead).
	option web_enabled '0'
	# Port to listen on (LAN only).
	option web_port '8088'
	# Optional password (basic-auth). Blank = LAN-only, no password.
	option web_password ''
UCI_EOF
    fi

    # If the migration carried over an enabled config, start the new service so
    # the peer comes back without a manual step (short outage during the swap is
    # expected; respawn keeps it up from here).
    if [ "$(uci -q get qetra.main.enabled)" = "1" ]; then
        /etc/init.d/qetra start 2>/dev/null || true
    else
        echo "qetra installed. Configure it, then start:"
        echo "  uci set qetra.main.enabled='1'"
        echo "  uci set qetra.main.management_url='https://<your-mgmt>:443'"
        echo "  uci set qetra.main.setup_key='<one-time-key>'   # first registration only"
        echo "  uci commit qetra && /etc/init.d/qetra restart"
    fi
}
exit 0
