#!/usr/bin/env bash
set -Eeuo pipefail

CONFIG="${1:?site config is required}"
BUNDLE_ROOT="${2:?bundle root is required}"
DEPLOY_ROOT="${3:?deploy root is required}"

command -v helm >/dev/null 2>&1 || { echo "helm is required" >&2; exit 1; }
command -v kubectl >/dev/null 2>&1 || { echo "kubectl is required" >&2; exit 1; }
command -v yq >/dev/null 2>&1 || { echo "yq v4 is required" >&2; exit 1; }

install_chart() {
  local release="$1"
  local namespace="$2"
  local chart="$3"
  local values_file="$4"
  shift 4
  [[ -f "$chart" ]] || {
    echo "Missing offline addon chart: $chart" >&2
    exit 1
  }
  kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl apply -f -
  helm upgrade --install "$release" "$chart" \
    --namespace "$namespace" \
    --values "$values_file" \
    --wait \
    --timeout 15m \
    "$@"
}

if [[ "$(yq -r '.addons.longhorn.enabled' "$CONFIG")" == "true" ]]; then
  LONGHORN_CHART="$BUNDLE_ROOT/$(yq -r '.addons.longhorn.chart' "$CONFIG")"
  LONGHORN_NAMESPACE="$(yq -r '.addons.longhorn.namespace' "$CONFIG")"
  install_chart \
    longhorn \
    "$LONGHORN_NAMESPACE" \
    "$LONGHORN_CHART" \
    "$DEPLOY_ROOT/addons/longhorn/values.yaml"
fi

if [[ "$(yq -r '.addons.gpuOperator.enabled' "$CONFIG")" == "true" ]]; then
  GPU_CHART="$BUNDLE_ROOT/$(yq -r '.addons.gpuOperator.chart' "$CONFIG")"
  GPU_NAMESPACE="$(yq -r '.addons.gpuOperator.namespace' "$CONFIG")"
  DRIVER_MANAGED="$(yq -r '.gpu.driverManagedByOperator' "$CONFIG")"
  install_chart \
    gpu-operator \
    "$GPU_NAMESPACE" \
    "$GPU_CHART" \
    "$DEPLOY_ROOT/addons/gpu/values.yaml" \
    --set "driver.enabled=$DRIVER_MANAGED"
fi
