#!/usr/bin/env bash
# Revert the NEXT-EP-POPUP shim injected into dev's index-dev.html on 2026-05-10.
#
# What it removes:
#   /* NEXT-EP-POPUP-BEGIN ... */ ... /* NEXT-EP-POPUP-END */
#
# Defaults to dev. Pass --prod to remove from prod's index.html instead.
# Idempotent: safe to re-run.
#
# After local edit, redeploy to nullstone via the same nsenter cp trick used
# for sub-label-shim revert (see comment at end).

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TARGET_DEV="$REPO_ROOT/web-overrides/index-dev.html"
TARGET_PROD="$REPO_ROOT/web-overrides/index.html"

TARGET="$TARGET_DEV"
ENV="dev"
if [[ "${1:-}" == "--prod" ]]; then
  TARGET="$TARGET_PROD"
  ENV="prod"
fi

if [[ ! -f "$TARGET" ]]; then
  echo "ERROR: $TARGET not found" >&2
  exit 1
fi

if ! grep -q "NEXT-EP-POPUP-BEGIN" "$TARGET"; then
  echo "shim already absent in $ENV — nothing to do"
  exit 0
fi

cp "$TARGET" "$TARGET.bak.$(date -u +%Y%m%dT%H%M%SZ)"
sed -i '/NEXT-EP-POPUP-BEGIN/,/NEXT-EP-POPUP-END/d' "$TARGET"

if grep -q "NEXT-EP-POPUP" "$TARGET"; then
  echo "ERROR: revert left orphan markers in $TARGET" >&2
  exit 2
fi

echo "reverted ($ENV). backup at $TARGET.bak.*"
echo
echo "Now redeploy to nullstone:"
if [[ "$ENV" == "dev" ]]; then
  echo "  scp $TARGET user@192.168.0.100:/tmp/index-dev-new.html"
  echo "  ssh user@192.168.0.100 'docker run --rm --privileged --pid=host --userns=host -v /opt:/opt -v /tmp:/tmp alpine nsenter -t 1 -m -u -i -n cp /tmp/index-dev-new.html /opt/docker/jellyfin-dev/web-overrides/index-dev.html'"
else
  echo "  scp $TARGET user@192.168.0.100:/tmp/arrflix-index.html"
  echo "  ssh user@192.168.0.100 'docker run --rm --privileged --pid=host --userns=host -v /opt:/opt -v /tmp:/tmp alpine nsenter -t 1 -m -u -i -n cp /tmp/arrflix-index.html /opt/docker/jellyfin/web-overrides/index.html'"
fi
echo "Then hard-refresh the browser (Ctrl+Shift+R)."
