#!/usr/bin/env bash
set -euo pipefail

# Zyphon Gateway Quickstart Setup Script
echo "=================================================="
echo "         ZYPHON GATEWAY SETUP & BOOTSTRAP         "
echo "=================================================="

WORKSPACE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$WORKSPACE_DIR"

# 1. Create required directories
echo "[1/5] Creating data & state directories..."
mkdir -p config
mkdir -p data/logs
mkdir -p data/state

chmod 0700 data/state
chmod 0755 data/logs

# 2. Setup example config manifests if not present
echo "[2/5] Initializing configuration manifests..."
for f in zyphon applications providers routing policies; do
  if [ ! -f "config/${f}.yaml" ] && [ -f "config/${f}.example.yaml" ]; then
    cp "config/${f}.example.yaml" "config/${f}.yaml"
    echo "  -> Created config/${f}.yaml from example"
  fi
done

# 3. Generate master key if .env not present
echo "[3/5] Setting up environment and security keys..."
if [ ! -f ".env" ]; then
  MASTER_KEY=$(openssl rand -hex 32)
  PEPPER=$(openssl rand -hex 16)
  cat <<EOF > .env
PORT=8080
ADMIN_PORT=8081
HOST=0.0.0.0
ZYPHON_MASTER_KEY=${MASTER_KEY}
ZYPHON_SYSTEM_PEPPER=${PEPPER}
ZYPHON_ADMIN_PASSWORD=zyphon-admin-secure
ZYPHON_CONFIG_DIR=./config
ZYPHON_DATA_DIR=./data
EOF
  chmod 0600 .env
  echo "  -> Generated .env with secure random ZYPHON_MASTER_KEY and permissions 0600"
else
  echo "  -> .env file already exists"
fi

# 4. Build workspace packages
echo "[4/5] Building packages and gateway..."
pnpm build

# 5. Summary
echo "[5/5] Setup complete!"
echo ""
echo "Next steps:"
echo "  1. Start Gateway:     pnpm --filter @zyphon/gateway start"
echo "  2. Start Dashboard:   pnpm --filter @zyphon/dashboard start"
echo "  3. Or run Docker:     docker compose up -d"
echo ""

