#!/usr/bin/env bash
# Install NEXUS_TEST_ADMIN_PASSWORD on production for prod_probe / E2E (not injected into API container).
#
# Usage (password must match admin login; never commit):
#   NEXUS_TEST_ADMIN_PASSWORD='your-admin-password' bash scripts/prod_probe_install.sh
#
# Writes to: /opt/nexus/docker/.env.prod (root 600)
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SECRETS="${ROOT}/deploy/nexus-1panel.secrets.sh"
if [[ -f "$SECRETS" ]]; then
  # shellcheck disable=SC1090
  source "$SECRETS"
fi

PW="${NEXUS_TEST_ADMIN_PASSWORD:-}"
if [[ -z "$PW" ]]; then
  echo "ERROR: set NEXUS_TEST_ADMIN_PASSWORD (same as admin login password)" >&2
  exit 1
fi
if [[ ${#PW} -lt 6 ]]; then
  echo "ERROR: password too short (min 6)" >&2
  exit 1
fi

SSH_HOST="${NEXUS_SSH:-nexus}"
SSH_OPTS=(-o BatchMode=yes -o ConnectTimeout=20)
[[ -n "${NEXUS_SSH_KEY:-}" ]] && SSH_OPTS+=(-i "${NEXUS_SSH_KEY}")

# Pass password via env on remote (single-quoted safe payload built in Python)
B64="$(PW="$PW" python3 -c 'import base64,os; print(base64.b64encode(os.environ["PW"].encode()).decode())')"
PROBE_IP="${NEXUS_PROBE_CLIENT_IP:-}"

ssh "${SSH_OPTS[@]}" "$SSH_HOST" "sudo bash -s" <<REMOTE
set -euo pipefail
ENV="/opt/nexus/docker/.env.prod"
[[ -f "\$ENV" ]] || { echo "missing \$ENV"; exit 1; }
PW=\$(python3 -c "import base64,os; print(base64.b64decode('${B64}').decode())")
LINE="NEXUS_TEST_ADMIN_PASSWORD=\${PW}"
if grep -q '^NEXUS_TEST_ADMIN_PASSWORD=' "\$ENV"; then
  sed -i "s|^NEXUS_TEST_ADMIN_PASSWORD=.*|\${LINE}|" "\$ENV"
else
  printf '%s\n' "\$LINE" >> "\$ENV"
fi
if [[ -n "${PROBE_IP}" ]]; then
  IPLINE="NEXUS_PROBE_CLIENT_IP=${PROBE_IP}"
  if grep -q '^NEXUS_PROBE_CLIENT_IP=' "\$ENV"; then
    sed -i "s|^NEXUS_PROBE_CLIENT_IP=.*|\${IPLINE}|" "\$ENV"
  else
    printf '%s\n' "\$IPLINE" >> "\$ENV"
  fi
fi
chmod 600 "\$ENV"
grep -q '^NEXUS_TEST_ADMIN_PASSWORD=' "\$ENV"
echo "OK: NEXUS_TEST_ADMIN_PASSWORD upserted in \$ENV (value not shown)"
REMOTE

echo "Run: bash scripts/prod_health_check.sh"
