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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

if ! command -v shenron >/dev/null 2>&1; then
  echo "shenron CLI not available; install the local package first (for example: python3 -m pip install -e \"$ROOT_DIR\")" >&2
  exit 1
fi

tmpdir="$(mktemp -d)"
asset_dir="$tmpdir/assets"
work_dir="$tmpdir/work"
version="$(awk -F': ' '$1 == "version" {gsub(/"/, "", $2); print $2; exit}' "$ROOT_DIR/helm/Chart.yaml")"
chart_pkg="shenron-${version}.tgz"

mkdir -p "$asset_dir" "$work_dir"
mkdir -p "$asset_dir/chart-root/shenron"
cp -R "$ROOT_DIR/helm/." "$asset_dir/chart-root/shenron/"
tar -czf "$asset_dir/$chart_pkg" -C "$asset_dir/chart-root" shenron
cat > "$asset_dir/index.yaml" <<EOF
apiVersion: v1
entries:
  shenron:
    - version: ${version}
      urls:
        - https://example.invalid/${chart_pkg}
generated: "2026-01-01T00:00:00Z"
EOF

shenron get \
  --helm \
  --release "$version" \
  --index-url "file://$asset_dir/index.yaml" \
  --base-url "file://$asset_dir/" \
  --dir "$work_dir/shenron-helm"

required=(
  "$work_dir/shenron-helm/Chart.yaml"
  "$work_dir/shenron-helm/values.yaml"
  "$work_dir/shenron-helm/helmfile-piccolo"
  "$work_dir/shenron-helm/helmfile-chiaotzu"
  "$work_dir/shenron-helm/node-piccolo.yaml"
  "$work_dir/shenron-helm/node-chiaotzu.yaml"
  "$work_dir/shenron-helm/replicas.yaml"
  "$work_dir/shenron-helm/templates/_helpers.tpl"
  "$work_dir/shenron-helm/templates/caddy-configmap.yaml"
  "$work_dir/shenron-helm/templates/caddy-deployment.yaml"
  "$work_dir/shenron-helm/templates/caddy-pvc.yaml"
  "$work_dir/shenron-helm/templates/caddy-service.yaml"
  "$work_dir/shenron-helm/templates/prometheus-configmap.yaml"
  "$work_dir/shenron-helm/templates/prometheus-deployment.yaml"
  "$work_dir/shenron-helm/templates/prometheus-rbac.yaml"
  "$work_dir/shenron-helm/templates/prometheus-service.yaml"
  "$work_dir/shenron-helm/templates/replica-manager-deployment.yaml"
  "$work_dir/shenron-helm/templates/replica-manager-service.yaml"
  "$work_dir/shenron-helm/templates/replica-manager-rbac.yaml"
  "$work_dir/shenron-helm/templates/worker-deployments.yaml"
  "$work_dir/shenron-helm/templates/worker-services.yaml"
)

for f in "${required[@]}"; do
  if [ ! -f "$f" ]; then
    echo "expected file not found after shenron get --helm: $f" >&2
    exit 1
  fi
done

echo "shenron get --helm downloaded and unpacked expected chart files"
