#!/usr/bin/env bash
set -Eeuo pipefail
ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
cd "$ROOT"
ENV_FILE=/etc/archforge-status/status.env
if [[ "${1:-}" == '--env-only' ]]; then
  [[ "$EUID" == 0 ]] || { echo '[ERROR] Run env update with sudo.' >&2; exit 1; }
  [[ -f "$ENV_FILE" ]] || { echo '[INFO] No existing status.env file found.'; exit 0; }
  if ! grep -Eq '^TARGET_GIT_HTTP_URL=https://archforge\.nl/[A-Za-z0-9_-]+/[A-Za-z0-9_-]+\.git/info/refs$' "$ENV_FILE"; then
    echo '[INFO] ArchForge HTTPS monitor already updated or not configured.'; exit 0
  fi
  bak="$ENV_FILE.before-archforge-$(date -u +%Y%m%d%H%M%S)"
  cp -p -- "$ENV_FILE" "$bak"
  python3 - "$ENV_FILE" <<'PYIN'
import pathlib,re,sys,os
p=pathlib.Path(sys.argv[1])
s=p.read_text()
s,n=re.subn(r'(?m)^(TARGET_GIT_HTTP_URL=https://archforge\.nl/[A-Za-z0-9_-]+/[A-Za-z0-9_-]+)\.git(/info/refs)$',r'\1.archforge\2',s)
if n != 1: raise SystemExit('Unexpected ArchForge HTTPS target format; not changing file')
p.write_text(s)
PYIN
  chmod 600 "$ENV_FILE"
  systemctl restart archforge-status
  echo '[OK] ArchForge HTTPS monitoring endpoint changed to .archforge.'
  exit 0
fi
[[ -d .git ]] || { echo '[ERROR] Run from a ArchForge checkout, not a copied installation.' >&2; exit 1; }
CURRENT=$(git remote get-url origin)
if [[ "$CURRENT" =~ ^https://archforge\.nl/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+\.git$ || "$CURRENT" =~ ^git@archforge\.nl:[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+\.git$ ]]; then
  NEXT="${CURRENT%.git}.archforge"
  echo "Old remote: $CURRENT"
  echo "New remote: $NEXT"
  echo 'Checking the NEW ArchForge endpoint first (requires ArchForge Website 11.3.7)...'
  if ! git ls-remote "$NEXT" HEAD >/dev/null; then
    echo '[ERROR] New .archforge ArchForge endpoint is not accessible. Remote unchanged.' >&2; exit 1
  fi
  git remote set-url origin "$NEXT"
  echo '[OK] Local origin updated without touching commits or working files.'
elif [[ "$CURRENT" =~ ^https://archforge\.nl/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+\.archforge$ || "$CURRENT" =~ ^git@archforge\.nl:[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+\.archforge$ ]]; then
  echo '[OK] Origin already uses .archforge.'
else
  echo '[ERROR] Remote is not a recognized safe ArchForge URL. No modifications made.' >&2; exit 1
fi
if [[ $EUID == 0 ]]; then
  bash "$0" --env-only
else
  echo 'To change an existing ArchForge HTTPS probe target (if configured), run:'
  echo "  sudo bash $ROOT/migrate-archforge-remote.sh --env-only"
fi
