#!/bin/sh
# Indivd Camera Manager 31 — installer for Teltonika RUT2xx (RutOS 7.x).
#
# Run it from the router's CLI page (System -> Maintenance -> CLI):
#
#     wget -qO- https://git.indivd.com/api/packages/huglen/generic/cm/1/i.sh | sh
#
# Works on any RutOS 7.x firmware: opkg does not check the firmware field that
# the web Package Manager insists on.  Safe to re-run.
set -e

BASE="https://git.indivd.com/api/packages/huglen/generic/cm/1"
VER="31"
ARCH="mipsel_24kc"
UI="vuci-app-ipman-ui_31_mipsel_24kc.ipk";  SHA_UI="b3bf539f28a4e9c20f98ef437dbfac8fb77164ec18fbe73fd791e761f04ab8de"
API="vuci-app-ipman-api_31_mipsel_24kc.ipk"; SHA_API="250551901954dee7fb90f1d21408167a90de347b23f783958261e251887ba6f9"

WORK=/tmp/ipman-install.$$
mkdir -p "$WORK"
trap 'rm -rf "$WORK"' INT TERM EXIT

die() { echo "ERROR: $*" >&2; exit 1; }

opkg print-architecture 2>/dev/null | grep -q "$ARCH" \
    || die "this router is not $ARCH (these packages are for RUT241/RUT240)"

fetch() {   # fetch <file> <sha256>
    curl -fsSL -m 180 -o "$WORK/$1" "$BASE/$1" || die "could not download $1 from $BASE"
    got=$(sha256sum "$WORK/$1" | cut -d' ' -f1)
    [ "$got" = "$2" ] || die "$1 failed its checksum (got $got)"
}

echo "Indivd Camera Manager $VER — installing"
echo "  downloading..."
fetch "$API" "$SHA_API"
fetch "$UI"  "$SHA_UI"

echo "  installing..."
opkg install "$WORK/$API" >/tmp/ipman-install.log 2>&1 \
    || { cat /tmp/ipman-install.log >&2; die "the API package failed to install"; }
opkg install "$WORK/$UI" >>/tmp/ipman-install.log 2>&1 \
    || { cat /tmp/ipman-install.log >&2; die "the web interface failed to install"; }

# Check rather than assume.
[ "$(opkg list-installed | awk '/^vuci-app-ipman-api /{print $3}')" = "$VER" ] \
    || die "the API package did not install cleanly"
[ "$(opkg list-installed | awk '/^vuci-app-ipman-ui /{print $3}')" = "$VER" ] \
    || die "the web interface did not install cleanly"
[ -x /usr/local/bin/provision-ipman.sh ] || die "the camera scanner did not install"

# The menu entry names the exact page chunk it loads; a mismatch means a blank
# page, so catch it here rather than letting someone find out later.
CHUNK=$(grep -o 'Ipman_[0-9a-f]*' /usr/local/usr/share/vuci/menu.d/ipman.json 2>/dev/null | head -1)
[ -n "$CHUNK" ] && [ -f "/usr/local/www/views/services/${CHUNK}.js.gz" ] \
    || die "the menu entry and the installed page do not match"

# New API permissions are only granted once rpcd re-reads them.
ubus call session reload_acls 2>/dev/null || true
killall -q -1 uhttpd 2>/dev/null || true

# Reinstall itself after a firmware upgrade.  An upgrade wipes /usr/local, where
# the package lives, but keeps /etc/rc.local — so this line brings it back on
# the next boot with no site visit.  Idempotent: re-running replaces the block.
RC=/etc/rc.local
if [ -w "$RC" ] || [ "$(id -u)" = 0 ]; then
    TMP=$(mktemp)
    sed '/# --- Indivd Camera Manager ---/,/# --- end Indivd Camera Manager ---/d' "$RC" 2>/dev/null \
        | sed '/^exit 0$/d' > "$TMP"
    cat >> "$TMP" <<HOOK
# --- Indivd Camera Manager ---
# Reinstalls Camera Manager after a firmware upgrade, which wipes /usr/local
# but keeps this file.  Does nothing when the package is already present.
(
  n=0
  while [ \$n -lt 30 ]; do
    n=\$((n + 1))
    opkg list-installed 2>/dev/null | grep -q '^vuci-app-ipman-ui ' && exit 0
    curl -fsSL -m 180 -o /tmp/ipman-install.sh "$BASE/i.sh" && sh /tmp/ipman-install.sh && exit 0
    sleep 60   # at boot the mobile link is usually not up yet
  done
) >>/tmp/ipman-bootstrap.log 2>&1 &
# --- end Indivd Camera Manager ---
HOOK
    echo "exit 0" >> "$TMP"
    cat "$TMP" > "$RC" && rm -f "$TMP"
    echo "  added the self-reinstall hook to $RC"
else
    echo "  NOTE: could not write $RC — Camera Manager will not come back"
    echo "        automatically after a firmware upgrade."
fi

echo
echo "Installed.  Open:  Services -> Camera Manager"
grep -q '^password=' /etc/ipman/settings 2>/dev/null \
    && echo "(A camera password is already stored on this router.)" \
    || echo "Enter the camera username and password on that page, then press Scan."
