#!/bin/bash
set -e

# scripts/fast-deploy-console
# Quickly updates Console, Authelia, and Ingress-Nginx bypassing CI/CD.

ENV=${1:-staging}

# Use the directory where the script is located to find the project root
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo "🚀 Fast-deploying infra components to $ENV..."
echo "📍 Project Root: $PROJECT_ROOT"

# Function to adopt existing resources into Helm
adopt_resource() {
  local kind=$1
  local name=$2
  local ns=$3
  local release=$4

  if kubectl get "$kind" "$name" -n "$ns" &>/dev/null; then
    echo "🏗️  Adopting $kind/$name into Helm release $release..."
    kubectl label "$kind" "$name" -n "$ns" "app.kubernetes.io/managed-by=Helm" --overwrite
    kubectl annotate "$kind" "$name" -n "$ns" "meta.helm.sh/release-name=$release" --overwrite
    kubectl annotate "$kind" "$name" -n "$ns" "meta.helm.sh/release-namespace=$ns" --overwrite
  fi
}

# 1. Update Authelia
echo "📦 Updating Authelia..."
# Adopt all resources including PVCs
adopt_resource secret authelia-secrets authelia authelia
adopt_resource configmap authelia-config authelia authelia
adopt_resource service authelia authelia authelia
adopt_resource deployment authelia authelia authelia
adopt_resource ingress authelia authelia authelia
adopt_resource pvc authelia-data authelia authelia

helm upgrade --install authelia "$PROJECT_ROOT/k8s/authelia" \
  --namespace authelia \
  --create-namespace \
  -f "$PROJECT_ROOT/k8s/authelia/values.yaml" \
  -f "$PROJECT_ROOT/k8s/authelia/values-$ENV.yaml"

# 2. Update Console (The Wiki)
echo "📦 Updating Console..."
adopt_resource secret console-html console console
adopt_resource service console console console
adopt_resource deployment console console console
adopt_resource ingress console console console

helm upgrade --install console "$PROJECT_ROOT/k8s/console" \
  --namespace console \
  --create-namespace \
  -f "$PROJECT_ROOT/k8s/console/values-$ENV.yaml"

# 3. Optional: Update Ingress-Nginx
if [[ "$2" == "--with-ingress" ]]; then
  echo "📦 Updating Ingress-Nginx..."
  kubectl rollout restart deployment/ingress-nginx-controller -n ingress-nginx
fi

echo "✅ Deployment complete. Checking status..."
kubectl get pods -n authelia
kubectl get pods -n console
