#!/usr/bin/env bash
# Reverse of runmefirst.sh
# Removes the Stonks Oracle deployment but preserves the PostgreSQL
# database/user, MinIO buckets, Redis data, and Ollama.
#
# Usage: bash runmelast.sh

set -uo pipefail

NAMESPACE="stonks-oracle"

echo "=== Stonks Oracle Teardown ==="

# --- 1. Uninstall Helm release ---
echo "[1/2] Uninstalling Helm release..."
helm uninstall stonks-oracle -n "$NAMESPACE" --wait 2>/dev/null \
  && echo "  Helm release removed." \
  || echo "  No Helm release found or already removed, continuing."

# --- 2. Clean up any stragglers ---
echo "[2/2] Cleaning up remaining resources in $NAMESPACE..."
kubectl delete deployments --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete statefulsets --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete services --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete ingresses --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete configmaps --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete secrets --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete networkpolicies --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete pvc --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true
kubectl delete jobs --all -n "$NAMESPACE" --ignore-not-found=true 2>/dev/null || true

# NOTE: namespace is kept intact so Helm labels persist for clean redeploy

echo ""
echo "=== Teardown complete ==="
echo ""
echo "Preserved (untouched):"
echo "  - Namespace $NAMESPACE (kept for Helm label compatibility)"
echo "  - PostgreSQL database 'stonks' and user 'stonks' in postgresql-service"
echo "  - MinIO buckets in minio-service"
echo "  - Redis data in redis-service"
echo "  - Ollama in ollama-service"
echo ""
echo "To redeploy: bash ~/sources/kube/stonks-oracle/runmefirst.sh"
