#!/usr/bin/env bash
# =====================================================================
# LogShip template cleanup — step 3: neutralize /opt/erp-nuxt-frontend/.env
# ---------------------------------------------------------------------
# Blanks every credential/endpoint that could reach production systems
# or external services (carriers, marketplaces, Sentry, push, NAS, IVR),
# and repoints public URLs at the clone's own IP.
#
#   03-neutralize-env.sh [TARGET]       # default 192.168.12.66
#   TARGET = an IP (public URLs become http://IP) or a domain like
#            app.blut24.com (public URLs become https://DOMAIN — TLS is
#            expected to terminate at an external proxy, like production)
#
# Kept working: local endpoints (URLV1/STRAPI*/POSTGREST/ELASTIC/PG_*),
# STRAPITOKEN + IDEMPIERETOKEN (local-instance tokens), AGGRID +
# NUXT_UI_PRO licenses, ID-based config (doctype/pricelist/country IDs).
# NOTE: IDEMPIERETOKEN is signed with the cloned iDempiere REST secret,
# which is identical to production's — rotate the REST secret when a
# clone is promoted to a real instance.
# =====================================================================
set -euo pipefail

TARGET="${1:-192.168.12.66}"
# IP -> http://IP ; domain -> https://DOMAIN (TLS at external proxy)
if [[ "$TARGET" =~ ^[0-9.]+$ ]]; then
  PUBLIC_URL="http://${TARGET}"
else
  PUBLIC_URL="https://${TARGET}"
fi
ENVF=/opt/erp-nuxt-frontend/.env

# --- production guard -----------------------------------------------------
if hostname | grep -q '^logship-production$'; then
  echo "FATAL: hostname is logship-production — refusing to run." >&2; exit 1
fi
if ip -4 addr show 2>/dev/null | grep -q '192\.168\.12\.72/'; then
  echo "FATAL: this host holds 192.168.12.72 (production IP) — refusing to run." >&2; exit 1
fi
[ -f "$ENVF" ] || { echo "FATAL: $ENVF not found" >&2; exit 1; }

# --- backup (delete in finalize phase!) -----------------------------------
if [ ! -f /root/env.production.bak ]; then
  cp "$ENVF" /root/env.production.bak
  chmod 600 /root/env.production.bak
  echo "backup written to /root/env.production.bak (REMOVE in finalize phase)"
fi

blank() {  # blank() KEY [KEY...] — set each existing KEY to ''
  for key in "$@"; do
    if grep -qE "^${key}=" "$ENVF"; then
      sed -i "s|^${key}=.*|${key}=''|" "$ENVF"
      echo "  blanked  $key"
    fi
  done
}

setval() {  # setval KEY VALUE
  if grep -qE "^${1}=" "$ENVF"; then
    sed -i "s|^${1}=.*|${1}='${2}'|" "$ENVF"
    echo "  set      $1=$2"
  fi
}

echo "Neutralizing $ENVF (public URL: $PUBLIC_URL)"

# external backends / prod systems
blank LARAVEL SENTRY_DSN
# carrier credentials (keep the *URL keys — harmless without creds)
blank SENDCLOUDPUBLICKEY SENDCLOUDPRIVATEKEY
blank DHLKEY DHLSECRET DHLUSER DHLPASS
blank DPDDELISID DPDPASSWORD DPDCUSTOMERNUMBER DPDDEPOT
# marketplaces
blank AMAZON_APP_ID AMAZON_LWA_CLIENT_ID AMAZON_LWA_CLIENT_SECRET AMAZON_OAUTH_REDIRECT_URI
blank JTL_FULFILLER_TOKEN
# push / camera / phone
blank VAPID_PUBLIC_KEY VAPID_PRIVATE_KEY FCM_SERVICE_ACCOUNT_JSON
blank SYNOLOGY_URL SYNOLOGY_USER SYNOLOGY_PASSWORD
blank IVR_SHARED_SECRET
# fresh encryption key (old one belongs to prod-encrypted blobs, now deleted)
if grep -qE '^CREDENTIAL_ENCRYPTION_KEY=' "$ENVF"; then
  setval CREDENTIAL_ENCRYPTION_KEY "$(openssl rand -hex 32)"
fi
# public URLs → clone target (IP or domain)
setval STRAPIPUBLIC    "${PUBLIC_URL}"
setval WEBAUTHN_ORIGIN "${PUBLIC_URL}"
setval WEBAUTHN_RP_ID  "${TARGET}"
setval SENTRY_ENVIRONMENT "template"

echo "Done. Restart the frontend to apply:  pm2 restart erpfrontend --update-env"
