#!/bin/bash

# setup-minio-bucket.sh
# Creates MinIO bucket and Kubernetes secrets for Ollama LLM server
# Runs as helmfile presync hook; all commands are idempotent
# Dependencies: kubectl, access to minio-az-a pod in storage namespace
# Environment: MINIO_ROOT_USER, MINIO_ROOT_PASSWORD (from Vault), AUTHENTIK_OLLAMA_CLIENT_ID, AUTHENTIK_OLLAMA_CLIENT_SECRET

set -e

echo "=== Step 1: Create and label llm namespace ==="
kubectl create namespace llm --dry-run=client -o yaml | kubectl apply -f -
kubectl label namespace llm \
  pod-security.kubernetes.io/enforce=baseline \
  pod-security.kubernetes.io/enforce-version=latest \
  --overwrite

echo "✓ llm namespace created/labeled"

echo ""
echo "=== Step 2: Create MinIO bucket riotpiao-models ==="

# Configure mc host inside MinIO pod
kubectl -n storage exec deployment/minio-az-a -- \
  mc config host add local http://localhost:9000 \
  "${MINIO_ROOT_USER}" "${MINIO_ROOT_PASSWORD}"

echo "✓ mc host configured"

# Create bucket (idempotent)
kubectl -n storage exec deployment/minio-az-a -- \
  mc mb --ignore-existing local/riotpiao-models

echo "✓ MinIO bucket riotpiao-models created (or already exists)"

# Enable versioning for model rollback safety
kubectl -n storage exec deployment/minio-az-a -- \
  mc version enable local/riotpiao-models

echo "✓ Versioning enabled on riotpiao-models bucket"

echo ""
echo "=== Step 3: Create ollama-minio Secret (MinIO credentials) ==="

kubectl create secret generic ollama-minio -n llm \
  --from-literal=endpoint="http://minio-az-a.storage:9000" \
  --from-literal=bucket="riotpiao-models" \
  --from-literal=access_key="${MINIO_ROOT_USER}" \
  --from-literal=secret_key="${MINIO_ROOT_PASSWORD}" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "✓ Secret ollama-minio created/updated"

echo ""
echo "=== Step 4: Create ollama-oidc Secret (Authentik credentials) ==="

kubectl create secret generic ollama-oidc -n llm \
  --from-literal=client_id="${AUTHENTIK_OLLAMA_CLIENT_ID}" \
  --from-literal=client_secret="${AUTHENTIK_OLLAMA_CLIENT_SECRET}" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "✓ Secret ollama-oidc created/updated"

echo ""
echo "=== Verification ==="
echo ""
echo "Run these commands to verify:"
echo "  kubectl -n llm get secret ollama-minio ollama-oidc"
echo "  kubectl -n storage exec deployment/minio-az-a -- mc ls local/riotpiao-models"
echo ""
echo "Setup complete!"
