#!/usr/bin/env bash
# CNPERP — first-time production bootstrap on Ubuntu 24.04 (Hetzner CPX31+)
# Run as root on a fresh server:
#
#   export CNPERP_DOMAIN=erp.cnpsolutions.co.bw
#   export CNPERP_DB_PASSWORD='your-strong-db-password'
#   export CNPERP_SECRET_KEY="$(openssl rand -base64 48)"
#   export CNPERP_LICENSE_ADMIN_SECRET="$(openssl rand -base64 32)"
#   bash bootstrap-production.sh
#
set -euo pipefail
exec > >(tee /tmp/cnperp-bootstrap.log) 2>&1

CNPERP_DOMAIN="${CNPERP_DOMAIN:-}"
CNPERP_DB_PASSWORD="${CNPERP_DB_PASSWORD:-}"
APP_DIR="/opt/cnperp"
APP_USER="cnperp"

# Reuse secrets from existing .env on resume/redeploy (avoid rotating God Mode password every deploy)
_load_env_value() {
  local key="$1" file="$APP_DIR/.env"
  [[ -f "$file" ]] || return 0
  grep -E "^${key}=" "$file" 2>/dev/null | head -1 | cut -d= -f2- || true
}
if [[ -z "${CNPERP_SECRET_KEY:-}" ]]; then
  existing_sk="$(_load_env_value SECRET_KEY)"
  [[ -n "$existing_sk" ]] && CNPERP_SECRET_KEY="$existing_sk"
fi
if [[ -z "${CNPERP_LICENSE_ADMIN_SECRET:-}" ]]; then
  existing_lic="$(_load_env_value LICENSE_ADMIN_SECRET)"
  existing_plat="$(_load_env_value PLATFORM_ADMIN_SECRET)"
  if [[ -n "$existing_lic" ]]; then
    CNPERP_LICENSE_ADMIN_SECRET="$existing_lic"
  elif [[ -n "$existing_plat" ]]; then
    CNPERP_LICENSE_ADMIN_SECRET="$existing_plat"
  fi
fi
if [[ -z "${CNPERP_LICENSE_SIGNING_SECRET:-}" ]]; then
  existing_sign="$(_load_env_value LICENSE_SIGNING_SECRET)"
  [[ -n "$existing_sign" ]] && CNPERP_LICENSE_SIGNING_SECRET="$existing_sign"
fi

CNPERP_SECRET_KEY="${CNPERP_SECRET_KEY:-$(openssl rand -base64 48 | tr -d '\n')}"
CNPERP_LICENSE_ADMIN_SECRET="${CNPERP_LICENSE_ADMIN_SECRET:-$(openssl rand -base64 32 | tr -d '\n')}"
CNPERP_LICENSE_SIGNING_SECRET="${CNPERP_LICENSE_SIGNING_SECRET:-$CNPERP_SECRET_KEY}"
GIT_REPO="${GIT_REPO:-https://github.com/cassidymug/cnperpdimensions.git}"
GIT_BRANCH="${GIT_BRANCH:-main}"
# Private repo: export GITHUB_TOKEN (read-only classic or fine-grained PAT)
if [[ -n "${GITHUB_TOKEN:-}" ]]; then
  GIT_REPO="https://x-access-token:${GITHUB_TOKEN}@github.com/cassidymug/cnperpdimensions.git"
fi
export GIT_TERMINAL_PROMPT=0
MARKETING_DOMAIN="${CNPERP_MARKETING_DOMAIN:-cnpsolutions.co.bw}"

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root: sudo bash $0"
  exit 1
fi

if [[ -z "$CNPERP_DOMAIN" || -z "$CNPERP_DB_PASSWORD" ]]; then
  echo "Required environment variables:"
  echo "  CNPERP_DOMAIN       — e.g. erp.cnpsolutions.co.bw"
  echo "  CNPERP_DB_PASSWORD  — PostgreSQL password for user cnperp"
  exit 1
fi

echo "=============================================="
echo " CNPERP production bootstrap"
echo " Domain: $CNPERP_DOMAIN"
echo " App dir: $APP_DIR"
echo "=============================================="

if [[ "${SKIP_SYSTEM_SETUP:-}" != "1" ]]; then
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq
  apt-get upgrade -y -qq
  apt-get install -y -qq git python3.12 python3.12-venv python3.12-dev python3-pip \
    build-essential libpq-dev \
    postgresql postgresql-contrib redis-server ufw fail2ban curl openssl

  if ! ufw status | grep -q "Status: active"; then
    ufw default deny incoming
    ufw default allow outgoing
    ufw allow 22/tcp
    ufw allow 80/tcp
    ufw allow 443/tcp
    ufw --force enable
  fi

  if ! id "$APP_USER" &>/dev/null; then
    useradd -m -s /bin/bash "$APP_USER"
  fi
  mkdir -p "$APP_DIR" /var/backups/cnperp /opt/cnperp/logs
  chown -R "$APP_USER:$APP_USER" "$APP_DIR" /var/backups/cnperp

  sudo -u postgres psql -tc "SELECT 1 FROM pg_roles WHERE rolname='$APP_USER'" | grep -q 1 || \
    sudo -u postgres psql -c "CREATE USER $APP_USER WITH PASSWORD '$CNPERP_DB_PASSWORD';"
  sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='cnperpdimensions'" | grep -q 1 || \
    sudo -u postgres psql -c "CREATE DATABASE cnperpdimensions OWNER $APP_USER;"
  sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE cnperpdimensions TO $APP_USER;" 2>/dev/null || true
else
  echo "Resume mode: skipping apt/PostgreSQL/firewall setup"
fi

# Application code
mkdir -p /var/backups/cnperp
chown -R "$APP_USER:$APP_USER" /var/backups/cnperp 2>/dev/null || true

if [[ -f /tmp/cnperp-requirements.txt ]]; then
  cp /tmp/cnperp-requirements.txt "$APP_DIR/requirements.txt"
  chown "$APP_USER:$APP_USER" "$APP_DIR/requirements.txt"
fi

if [[ "${SKIP_GIT_CLONE:-}" == "1" ]]; then
  echo "Using application code uploaded from your PC (SKIP_GIT_CLONE=1)..."
  mkdir -p "$APP_DIR"
  chown -R "$APP_USER:$APP_USER" "$APP_DIR"
  if [[ ! -f "$APP_DIR/requirements.txt" ]]; then
    echo "ERROR: $APP_DIR/requirements.txt missing. Upload code before bootstrap."
    exit 1
  fi
elif [[ -d "$APP_DIR" && ! -d "$APP_DIR/.git" ]]; then
  echo "Removing incomplete $APP_DIR from a prior bootstrap attempt..."
  rm -rf "$APP_DIR"
fi

if [[ "${SKIP_GIT_CLONE:-}" != "1" ]]; then
  mkdir -p "$APP_DIR"
  chown -R "$APP_USER:$APP_USER" "$APP_DIR"
  if [[ -d "$APP_DIR/.git" ]]; then
    sudo -u "$APP_USER" bash -c "cd $APP_DIR && git fetch origin && git checkout $GIT_BRANCH && git pull origin $GIT_BRANCH"
  else
    echo "Cloning application from GitHub (branch $GIT_BRANCH)..."
    git clone --branch "$GIT_BRANCH" --depth 1 "$GIT_REPO" "$APP_DIR"
    chown -R "$APP_USER:$APP_USER" "$APP_DIR"
  fi
fi

if [[ "${RESUME_PIP_ONLY:-}" != "1" ]]; then
  if [[ -d "$APP_DIR/.venv" ]] && ! "$APP_DIR/.venv/bin/python" -c "import fastapi" 2>/dev/null; then
    echo "Removing incomplete virtualenv from a prior bootstrap attempt..."
    rm -rf "$APP_DIR/.venv"
  fi
  sudo -u "$APP_USER" bash -c "set -euo pipefail
    cd $APP_DIR
    python3.12 -m venv .venv
    source .venv/bin/activate
    pip install --upgrade pip 'setuptools>=69' wheel
    PIP_NO_BUILD_ISOLATION=1 pip install -r requirements.txt
    chmod +x deploy/auto_update.sh deploy/hetzner/deploy.sh deploy/hetzner/run-migrations.sh 2>/dev/null || true
  "
else
  echo "Resume mode: pip install only (Python 3.12 wheels)"
  sudo -u "$APP_USER" bash -c "set -euo pipefail
    cd $APP_DIR
    test -d .venv || python3.12 -m venv .venv
    source .venv/bin/activate
    pip install --upgrade pip 'setuptools>=69' wheel
    PIP_NO_BUILD_ISOLATION=1 pip install -r requirements.txt
    chmod +x deploy/auto_update.sh deploy/hetzner/deploy.sh deploy/hetzner/run-migrations.sh 2>/dev/null || true
  "
fi

SERVER_IP="${SERVER_IP:-$(curl -fsS --max-time 5 ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')}"

if [[ -f "$APP_DIR/.env" ]]; then
  echo "Preserving existing SECRET_KEY / LICENSE_ADMIN_SECRET from $APP_DIR/.env (resume deploy)"
fi

# .env
LICENSE_URL="https://${CNPERP_DOMAIN}"
CORS="https://${CNPERP_DOMAIN}"

cat > "$APP_DIR/.env" <<ENVFILE
ENVIRONMENT=production
DEBUG=false
DEPLOYMENT_MODE=cloud

SECRET_KEY=${CNPERP_SECRET_KEY}
DATABASE_URL=postgresql://${APP_USER}:${CNPERP_DB_PASSWORD}@127.0.0.1:5432/cnperpdimensions
REDIS_URL=redis://127.0.0.1:6379/0

LICENSE_CLOUD_URL=${LICENSE_URL}
CORS_ORIGINS=${CORS}

LICENSE_ENFORCEMENT=true
LICENSE_REQUIRED_FOR_SETUP=true
ALLOW_LEGACY_UNLICENSED=false
LICENSE_ADMIN_SECRET=${CNPERP_LICENSE_ADMIN_SECRET}
LICENSE_SIGNING_SECRET=${CNPERP_LICENSE_SIGNING_SECRET}

GITHUB_REPO=cassidymug/cnperpdimensions
GITHUB_TOKEN=${GITHUB_TOKEN:-}
UPDATE_ENABLED=true
UPDATE_BRANCH=main

ACCESS_TOKEN_EXPIRE_MINUTES=480

PLATFORM_ADMIN_SECRET=${CNPERP_LICENSE_ADMIN_SECRET}
PLATFORM_ADMIN_TOKEN_HOURS=0
CNP_SUPPORT_ENABLED=true
CNP_SUPPORT_USERNAME=cnpadmin
CNP_SUPPORT_PASSWORD=CHANGE_ME_AFTER_DEPLOY

COMPANY_PHONE_PRIMARY=+26774818826
COMPANY_PHONE_ALT=+26777122880
ERP_ONLY=true
COMPANY_WEBSITE=https://${CNPERP_DOMAIN}
MARKETING_PUBLIC_URL=https://${MARKETING_DOMAIN}
ERP_PUBLIC_URL=https://${CNPERP_DOMAIN}
MARKETING_HOSTS=${MARKETING_DOMAIN},www.${MARKETING_DOMAIN}
ERP_HOSTS=${CNPERP_DOMAIN},${SERVER_IP}
WHATSAPP_DEFAULT_NUMBER=26774818826
ENVFILE
chown "$APP_USER:$APP_USER" "$APP_DIR/.env"
chmod 600 "$APP_DIR/.env"

if [[ "${RESUME_PIP_ONLY:-}" != "1" ]]; then
  sed -i 's/\r$//' "$APP_DIR/deploy/hetzner/init-db-schema.sh" 2>/dev/null || true
  chmod +x "$APP_DIR/deploy/hetzner/init-db-schema.sh"
  echo "Creating base database schema from models..."
  sudo -u "$APP_USER" "$APP_DIR/deploy/hetzner/init-db-schema.sh" "$APP_DIR"

  sed -i 's/\r$//' "$APP_DIR/deploy/hetzner/run-migrations.sh" 2>/dev/null || true
  chmod +x "$APP_DIR/deploy/hetzner/run-migrations.sh"
  sudo -u "$APP_USER" "$APP_DIR/deploy/hetzner/run-migrations.sh" "$APP_DIR"
else
  echo "Resume mode: skipping init-db-schema and migrations"
fi

# systemd
cp "$APP_DIR/deploy/hetzner/cnperp.service" /etc/systemd/system/cnperp.service
systemctl daemon-reload
systemctl enable cnperp
systemctl restart cnperp

# Caddy
if ! command -v caddy &>/dev/null; then
  apt-get install -y -qq debian-keyring debian-archive-keyring apt-transport-https
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
  curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
  apt-get update -qq
  apt-get install -y -qq caddy
fi

sed -e "s/__CNPERP_DOMAIN__/${CNPERP_DOMAIN}/g" \
    -e "s/__MARKETING_DOMAIN__/${MARKETING_DOMAIN}/g" \
    -e "s/__SERVER_IP__/${SERVER_IP}/g" \
    -e "s/erp.cnpsolutions.co.bw/${CNPERP_DOMAIN}/g" \
    -e "s/cnpsolutions.co.bw/${MARKETING_DOMAIN}/g" \
  "$APP_DIR/deploy/hetzner/Caddyfile.example" > /etc/caddy/Caddyfile
systemctl enable caddy
systemctl reload caddy || systemctl restart caddy

sleep 3
echo ""
echo "=============================================="
if systemctl is-active --quiet cnperp; then
  echo " cnperp service: RUNNING"
else
  echo " cnperp service: FAILED — run: journalctl -u cnperp -n 50"
fi
if systemctl is-active --quiet caddy; then
  echo " caddy TLS proxy: RUNNING"
else
  echo " caddy: check journalctl -u caddy"
fi
echo "=============================================="
echo ""
echo "NEXT STEPS:"
echo "  1. Point DNS A record for ${CNPERP_DOMAIN} → this server's public IP"
echo "  2. Open https://${CNPERP_DOMAIN}/setup (after DNS + TLS propagate)"
echo "  3. Save license admin secret (shown once below)"
echo "  4. Marketing site: https://${CNPERP_DOMAIN}/"
echo "  5. ERP login: https://${CNPERP_DOMAIN}/static/login.html"
echo ""
echo "LICENSE_ADMIN_SECRET=${CNPERP_LICENSE_ADMIN_SECRET}"
echo "PLATFORM_ADMIN_SECRET=${CNPERP_LICENSE_ADMIN_SECRET}  (God Mode /platform-admin)"
echo "(Change CNP_SUPPORT_PASSWORD in ${APP_DIR}/.env before go-live)"
echo ""
echo "Secrets also in ${APP_DIR}/.env on server"
