#!/bin/bash
# Deploy Crossplane provider to Kubernetes
# DEPLOY-021: Deploy provider to Kubernetes

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROVIDER_DIR="$PROJECT_ROOT/crossplane-provider-proxmox"

echo "=== Deploying Crossplane Provider ==="
echo ""

# Check prerequisites
if ! command -v kubectl &> /dev/null; then
    echo "✗ kubectl is not installed or not in PATH"
    exit 1
fi

if ! kubectl cluster-info &> /dev/null; then
    echo "✗ Cannot connect to Kubernetes cluster"
    exit 1
fi

echo "✓ Kubernetes cluster is accessible"
echo ""

# Check if Crossplane is installed
if ! kubectl get namespace crossplane-system &> /dev/null; then
    echo "⚠ Crossplane namespace not found"
    echo "  Installing Crossplane..."
    kubectl create namespace crossplane-system || true
    echo "  Please install Crossplane first:"
    echo "    helm repo add crossplane-stable https://charts.crossplane.io/stable"
    echo "    helm install crossplane --namespace crossplane-system crossplane-stable/crossplane"
    echo ""
    read -p "Press Enter once Crossplane is installed, or Ctrl+C to exit..."
fi

cd "$PROVIDER_DIR"

# Set image (can be overridden)
IMG="${IMG:-ghcr.io/sankofa/crossplane-provider-proxmox:latest}"

# Install CRDs
echo "Installing CRDs..."
make install

# Deploy provider
echo ""
echo "Deploying provider..."
make deploy IMG="$IMG"

# Wait for provider to be ready
echo ""
echo "Waiting for provider to be ready..."
kubectl wait --for=condition=healthy provider.pkg.crossplane.io \
  crossplane-provider-proxmox --timeout=300s || true

# Show status
echo ""
echo "=== Provider Status ==="
kubectl get providers
kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox

echo ""
echo "=== Provider deployed successfully ==="
echo ""
echo "Next steps:"
echo "1. Create ProviderConfig secret:"
echo "   kubectl create secret generic proxmox-credentials \\"
echo "     --from-file=credentials.json=<path-to-credentials> \\"
echo "     -n crossplane-system"
echo ""
echo "2. Apply ProviderConfig:"
echo "   kubectl apply -f $PROJECT_ROOT/crossplane-provider-proxmox/examples/provider-config.yaml"
