#!/bin/bash
# Deploy rdev to k3s cluster

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Ensure kubeconfig is set
if [[ -z "$KUBECONFIG" ]]; then
    echo "Error: KUBECONFIG not set"
    echo "Run: export KUBECONFIG=~/.kube/orchard9-k3sf.yaml"
    exit 1
fi

echo "Deploying rdev to k3s..."
echo "Using kubeconfig: $KUBECONFIG"
echo ""

# Verify cluster access
echo "Verifying cluster access..."
kubectl cluster-info > /dev/null || {
    echo "Error: Cannot connect to cluster"
    exit 1
}

# Note: Claude auth is stored in a PVC, not a secret
# User will authenticate via: kubectl exec -it -n rdev claudebox-0 -- claude

# Check if ghcr-secret exists in rdev namespace
if ! kubectl get secret ghcr-secret -n rdev > /dev/null 2>&1; then
    echo ""
    echo "Copying ghcr-secret from apps namespace to rdev..."
    kubectl get secret ghcr-secret -n apps -o yaml | \
        sed 's/namespace: apps/namespace: rdev/' | \
        kubectl apply -f - 2>/dev/null || {
        echo "ghcr-secret not found in apps namespace, checking default..."
        kubectl get secret ghcr-secret -n default -o yaml | \
            sed 's/namespace: default/namespace: rdev/' | \
            kubectl apply -f -
    }
fi

# Apply manifests
echo ""
echo "Applying Kustomize manifests..."
kubectl apply -k "$PROJECT_ROOT/deployments/k8s/base"

echo ""
echo "Waiting for claudebox pod to be ready..."
kubectl wait --for=condition=ready pod -l app=claudebox -n rdev --timeout=120s || {
    echo ""
    echo "Pod not ready. Check status with:"
    echo "  kubectl get pods -n rdev"
    echo "  kubectl describe pod claudebox-0 -n rdev"
    echo "  kubectl logs claudebox-0 -n rdev"
    exit 1
}

echo ""
echo "Deployment complete!"
echo ""
echo "Verify with:"
echo "  kubectl exec -n rdev claudebox-0 -- claude --version"
echo ""
echo "Test Claude:"
echo "  kubectl exec -it -n rdev claudebox-0 -- claude \"say hello\""
