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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CHART_DIR="$ROOT/deployments/charts/ops-server"
HELM_CONTROLLER_VERSION="${HELM_CONTROLLER_VERSION:-v1.3.0}"
SOURCE_CONTROLLER_VERSION="${SOURCE_CONTROLLER_VERSION:-v1.7.4}"
TMP_FILES=()

cleanup() {
  local file
  for file in "${TMP_FILES[@]}"; do
    rm -f "$file"
  done
}

trap cleanup EXIT

track_tmp() {
  TMP_FILES+=("$1")
}

prepend_header() {
  local source_file="$1"
  local source_url="$2"
  local version="$3"
  local version_of="$4"
  local output_file="$5"

  {
    printf '# Source: %s\n' "$source_url"
    printf '# Version: %s\n' "${version#v}"
    printf '# VersionOf: %s\n' "$version_of"
    cat "$source_file"
  } > "$output_file"
}

refresh_crd() {
  local target_file="$1"
  local source_url="$2"
  local version="$3"
  local version_of="$4"
  local download_file="${target_file}.download"
  local output_file="${target_file}.tmp"

  track_tmp "$download_file"
  track_tmp "$output_file"

  curl -fsSL "$source_url" -o "$download_file"
  prepend_header "$download_file" "$source_url" "$version" "$version_of" "$output_file"
  rm -f "$download_file"
  mv "$output_file" "$target_file"
}

refresh_crd \
  "$CHART_DIR/crds/helm-controller-crds.yaml" \
  "https://github.com/fluxcd/helm-controller/releases/download/${HELM_CONTROLLER_VERSION}/helm-controller.crds.yaml" \
  "$HELM_CONTROLLER_VERSION" \
  "fluxcd-helm-controller"
refresh_crd \
  "$CHART_DIR/crds/source-controller-crds.yaml" \
  "https://github.com/fluxcd/source-controller/releases/download/${SOURCE_CONTROLLER_VERSION}/source-controller.crds.yaml" \
  "$SOURCE_CONTROLLER_VERSION" \
  "fluxcd-source-controller"

python - \
  "$CHART_DIR/values.yaml" \
  "$CHART_DIR/README.md" \
  "$SOURCE_CONTROLLER_VERSION" \
  "$HELM_CONTROLLER_VERSION" <<'PY'
from pathlib import Path
import re
import sys

values_path = Path(sys.argv[1])
readme_path = Path(sys.argv[2])
source_version = sys.argv[3]
helm_version = sys.argv[4]


def rewrite(path: Path, replacements: list[tuple[str, str]], label: str) -> None:
    content = path.read_text()
    for pattern, replacement in replacements:
        content, count = re.subn(pattern, replacement, content, count=1)
        if count != 1:
            raise SystemExit(f"failed to update {label} with pattern: {pattern}")

    tmp_path = path.with_name(f"{path.name}.tmp")
    tmp_path.write_text(content)
    tmp_path.replace(path)


rewrite(
    values_path,
    [
        (
            r'(sourceController:\n  image:\n    repository: fluxcd/source-controller\n    tag: )"[^"]+"',
            rf'\1"{source_version}"',
        ),
        (
            r'(helmController:\n  image:\n    repository: fluxcd/helm-controller\n    tag: )"[^"]+"',
            rf'\1"{helm_version}"',
        ),
    ],
    "values.yaml",
)

rewrite(
    readme_path,
    [
        (
            r'(sourceController:\n  image:\n    repository: fluxcd/source-controller\n    tag: )"[^"]+"',
            rf'\1"{source_version}"',
        ),
        (
            r'(helmController:\n  image:\n    repository: fluxcd/helm-controller\n    tag: )"[^"]+"',
            rf'\1"{helm_version}"',
        ),
    ],
    "README.md",
)
PY
