#!/bin/bash

# -------------------------------------------------------------------------
# This script synchronizes the local-csi-driver charts from the original
# repo to the Kaito project. It:
# 1. Clones the Azure/local-csi-driver repo at a specific revision
# 2. Uses Helm to template the driver chart with specific webhook settings
# 3. Applies a patch to adapt the chart for Kaito's requirements
# 4. Saves the result to Kaito's chart templates directory
# -------------------------------------------------------------------------

SCRIPT_DIR="$(realpath "$(dirname "$0")")"

REPO=https://github.com/Azure/local-csi-driver.git
REVISION="06932013f5ab544172636a3d907a551914f64b68"

TEMP_DIR=$(mktemp -d)
REPO_DIR="$TEMP_DIR/local-csi-driver"

set -euo pipefail

cleanup() {
  echo "Cleaning up temporary directory: $TEMP_DIR"
  rm -rf "$TEMP_DIR"
}

# Set trap to ensure cleanup on script exit or interruption
trap cleanup EXIT INT TERM

echo "Created temporary directory: $TEMP_DIR"

echo "Cloning $REPO repository..."
git clone "$REPO" "$REPO_DIR"
echo "Checking out revision: $REVISION"
(cd "$REPO_DIR" && git checkout "$REVISION") || { echo "Failed to checkout revision $REVISION"; exit 1; }

helm template --release-name local-csi-driver \
  --set image.driver.tag="0.0.1-latest" \
  --set webhook.enforceEphemeral.enabled=false \
  --set webhook.hyperconverged.enabled=false \
  --set observability.metrics.enabled=false \
  "$REPO_DIR/charts/latest/" > "$REPO_DIR/local-csi-driver-charts.yaml"

TARGET_FILE="$SCRIPT_DIR/../../charts/kaito/workspace/templates/local-csi-driver-ds.yaml"

patch "$REPO_DIR/local-csi-driver-charts.yaml" "$SCRIPT_DIR/local-csi-driver-charts.diff" \
  -o "$TARGET_FILE"

# Add warning header to the generated file
sed -i '1i\
# ---------------------------------------------------------\
# WARNING: This file is generated by:\
# ./hack/local-csi-driver-charts-sync/local-csi-driver-charts-sync.sh\
#\
# DO NOT MODIFY THIS FILE DIRECTLY!\
# ---------------------------------------------------------\
' "$TARGET_FILE"
