#!/usr/bin/env bash
set -u

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
TAIL_LINES="${1:-120}"

if [[ ! "$TAIL_LINES" =~ ^[0-9]+$ ]]; then
  TAIL_LINES=120
fi

step() {
  local msg="$1"
  printf '\n[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$msg"
}

step "Start strongswan migration check"
echo "workspace: $ROOT_DIR"
echo "tail_lines: $TAIL_LINES"

cd "$ROOT_DIR" || {
  echo "ERROR: cannot cd to workspace"
  exit 1
}

step "1/6 moved files in mylib4ikev2svr"
find mylib4ikev2svr -maxdepth 1 -type f -name 'strongswan_*.php' | sort

step "2/6 leftover files in mylib (should be empty)"
leftover="$(find mylib -maxdepth 1 -type f -name 'strongswan_*.php' | sort)"
if [[ -n "$leftover" ]]; then
  echo "$leftover"
else
  echo "OK: no leftover strongswan_*.php in mylib"
fi

step "3/6 runtime old-path refs (/mylib/strongswan_) excluding backups/vendor-like dirs"
refs_runtime="$(grep -RIn \
  --include='*.php' --include='*.py' \
  --exclude-dir=.git --exclude-dir=.vscode --exclude-dir=data --exclude-dir=mylib_PREV --exclude-dir=mylib4ikev2svr \
  '/mylib/strongswan_' . 2>/dev/null || true)"
if [[ -n "$refs_runtime" ]]; then
  echo "$refs_runtime"
else
  echo "OK: no runtime refs found"
fi

step "4/6 comment+generator refs in mylib4ikev2svr (informational)"
refs_info="$(grep -RIn --include='*.php' --include='*.py' '/mylib/strongswan_' mylib4ikev2svr 2>/dev/null || true)"
if [[ -n "$refs_info" ]]; then
  echo "$refs_info" | head -n "$TAIL_LINES"
  total_info="$(echo "$refs_info" | wc -l | tr -d ' ')"
  echo "info_total_lines=$total_info (showing up to $TAIL_LINES)"
else
  echo "OK: no informational refs found"
fi

step "5/6 php lint key files"
php -l adm/vpn_msg_form.php || exit 2
find mylib4ikev2svr -type f -name 'strongswan_*.php' -print0 | xargs -0 -n1 php -l || exit 3

step "6/6 git status (best effort)"
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  git -c core.quotepath=false status --short
else
  echo "INFO: not a git repository here (skip git status)"
fi

step "Done"
