#!/usr/bin/env bash
# vps-control-plane.sh - Bootstrap script for VPS control plane

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
RUNTIME_DIR="/opt/homelab"
VPS_CONFIG="$REPO_ROOT/hosts/vps/runtime"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

log "Starting VPS control plane bootstrap..."

# 1. Validate Docker availability
if ! command -v docker &> /dev/null; then
    error "Docker is not installed. Please install Docker first."
fi

# 2. Validate compose plugin
if ! docker compose version &> /dev/null; then
    error "Docker Compose plugin is not installed."
fi

log "Docker and Compose plugin verified."

# 3. Create filesystem-first runtime structure
log "Creating filesystem-first runtime structure in $RUNTIME_DIR..."
sudo mkdir -p "$RUNTIME_DIR/events" \
             "$RUNTIME_DIR/state" \
             "$RUNTIME_DIR/world" \
             "$RUNTIME_DIR/actions/pending" \
             "$RUNTIME_DIR/actions/approved" \
             "$RUNTIME_DIR/actions/running" \
             "$RUNTIME_DIR/actions/completed" \
             "$RUNTIME_DIR/actions/failed" \
             "$RUNTIME_DIR/actions/rejected" \
             "$RUNTIME_DIR/config" \
             "$RUNTIME_DIR/logs"

# 4. Set permissions
log "Setting permissions..."
sudo chown -R $USER:$USER "$RUNTIME_DIR"
chmod -R 755 "$RUNTIME_DIR"

# 5. Install environment file
log "Installing environment configuration..."
if [ ! -f "$RUNTIME_DIR/config/control-plane.env" ]; then
    cp "$VPS_CONFIG/control-plane/env.example" "$RUNTIME_DIR/config/control-plane.env"
    log "Created $RUNTIME_DIR/config/control-plane.env from template."
else
    warn "Environment file already exists, skipping installation."
fi

# 6. Build and start the control plane
log "Building and starting control plane services..."
cd "$REPO_ROOT/services/control-plane"
docker compose build
docker compose up -d

log "VPS control plane bootstrap complete!"

echo -e "\n${YELLOW}Verification commands:${NC}"
echo "1. Check container status: docker compose ps"
echo "2. Check operator UI: curl http://localhost:8080/summary"
echo "3. Validate world state: ls -l $RUNTIME_DIR/world"
echo "4. Monitor events: tail -f $RUNTIME_DIR/events/*/*/*.json"
