#!/bin/bash
# =============================================================================
# One-time setup for the staging environment
# Run this once on dashboard-dev to prepare the staging deployment target.
# =============================================================================

set -e

STAGING_DIR="/home/cve-dashboard-staging"
SERVICE_FILE="deploy/cve-backend-staging.service"

echo "Setting up staging environment..."

# Create staging directory if it doesn't exist
if [ ! -d "$STAGING_DIR" ]; then
    echo "Creating $STAGING_DIR..."
    mkdir -p "$STAGING_DIR"
fi

# Copy the staging systemd service
echo "Installing staging systemd service..."
sudo cp "$SERVICE_FILE" /etc/systemd/system/cve-backend-staging.service
sudo systemctl daemon-reload
sudo systemctl enable cve-backend-staging

# Create staging .env from production template (adjust port)
if [ ! -f "$STAGING_DIR/backend/.env" ]; then
    echo "Creating staging .env..."
    mkdir -p "$STAGING_DIR/backend"
    if [ -f "/home/cve-dashboard/backend/.env" ]; then
        cp /home/cve-dashboard/backend/.env "$STAGING_DIR/backend/.env"
        # Override port for staging
        sed -i 's/^PORT=.*/PORT=3100/' "$STAGING_DIR/backend/.env"
        # If PORT line doesn't exist, add it
        grep -q "^PORT=" "$STAGING_DIR/backend/.env" || echo "PORT=3100" >> "$STAGING_DIR/backend/.env"
    else
        echo "PORT=3100" > "$STAGING_DIR/backend/.env"
        echo "WARNING: No production .env found. You'll need to configure $STAGING_DIR/backend/.env manually."
    fi
fi

echo ""
echo "Staging setup complete."
echo "  Directory: $STAGING_DIR"
echo "  Service:   cve-backend-staging"
echo "  Port:      3100"
echo ""
echo "Next steps:"
echo "  1. Verify $STAGING_DIR/backend/.env has correct DATABASE_URL (use a separate staging DB if possible)"
echo "  2. Run a pipeline on main/master to trigger the first staging deploy"
