#!/usr/bin/env bash
# Set a new God Mode secret on the server and restart cnperp.
set -euo pipefail
[[ "$(id -u)" -eq 0 ]] || { echo "Run as root"; exit 1; }

ENV_FILE="${1:-/opt/cnperp/.env}"
NEW="${2:-$(openssl rand -base64 32 | tr -d '\n')}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing $ENV_FILE"
  exit 1
fi

if grep -q '^PLATFORM_ADMIN_SECRET=' "$ENV_FILE"; then
  sed -i "s|^PLATFORM_ADMIN_SECRET=.*|PLATFORM_ADMIN_SECRET=${NEW}|" "$ENV_FILE"
else
  echo "PLATFORM_ADMIN_SECRET=${NEW}" >> "$ENV_FILE"
fi
if grep -q '^LICENSE_ADMIN_SECRET=' "$ENV_FILE"; then
  sed -i "s|^LICENSE_ADMIN_SECRET=.*|LICENSE_ADMIN_SECRET=${NEW}|" "$ENV_FILE"
else
  echo "LICENSE_ADMIN_SECRET=${NEW}" >> "$ENV_FILE"
fi
chmod 600 "$ENV_FILE"
chown cnperp:cnperp "$ENV_FILE" 2>/dev/null || true

systemctl restart cnperp
sleep 2
systemctl is-active cnperp

echo ""
echo "=============================================="
echo " God Mode secret updated (copy now — shown once)"
echo "=============================================="
echo ""
echo "  URL:     https://erp.cnpsolutions.co.bw/platform-admin"
echo "  Secret:  ${NEW}"
echo ""
echo "Paste into 'Platform secret' on the login form."
echo "=============================================="
