#!/bin/sh
# opkg wrapper: run the static opkg with our conf + force-space, then (1) regen
# tool wrappers, and (2) run any deferred postinsts (offline_root defers them).
# PATH gets /tmp/wgetssl so opkg's `wget` calls resolve to the REAL busybox-1.31
# wget (HTTPS via its ssl_client applet). Self-heal the symlink if boot hasn't.
[ -e /tmp/wgetssl/wget ] || { mkdir -p /tmp/wgetssl; ln -sf /tmp/vanilla/busybox /tmp/wgetssl/wget; ln -sf /tmp/vanilla/busybox /tmp/wgetssl/ssl_client; }
export PATH="/tmp/wgetssl:$PATH"

# offline_root ALSO defers prerm — opkg prints "Removing" but never runs the
# maintainer prerm, so `opkg remove` would delete a package's files while its
# service kept respawning (inittab line + daemon left behind). Run each named
# package's prerm HERE, before opkg-bin deletes it, with IPKG_INSTROOT=/tmp so
# the ${IPKG_INSTROOT}/opt/.. paths resolve. This is the teardown mirror of the
# ax10-configure postinst step below. (Args are processed in the given order, so
# `opkg remove ax10-luci ax10-wifi ax10-svc` tears down luci/wifi while ax10-svc
# — which their prerms call — is still present.)
if [ "$1" = remove ]; then
    for a in "$@"; do
        case "$a" in remove|-*) continue ;; esac
        pr="/tmp/opt/lib/opkg/info/$a.prerm"
        [ -f "$pr" ] && IPKG_INSTROOT=/tmp sh "$pr" remove 2>/dev/null
    done
fi

/tmp/opt/bin/opkg-bin -f /tmp/opt/etc/opkg.conf --force-space "$@"
rc=$?
/tmp/opt/opt-genwrappers.sh 2>/dev/null
case "$1" in
    install|configure) /tmp/opt/ax10-configure 2>/dev/null ;;
esac
exit $rc
