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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
EXT_DIR="$ROOT/extensions"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

mkdir -p "$EXT_DIR"

# Format: name|repo_url|branch|dest_subdir_under_extensions
REPOS=(
  "botbox3000|https://github.com/jondale/botbox3000.git|main|botbox3000"
  "km-living-hinge|https://github.com/KnoxMakers/km-living-hinge.git|main|km-living-hinge"
  "km-plot|https://git.knoxmakers.org/KnoxMakers/km-plot.git|main|km-plot"
)

sync_one() {
  local name="$1" url="$2" branch="$3" dest="$4"
  local work="$TMP/$name"
  local target="$EXT_DIR/$dest"

  echo "==> Sync $name from $url ($branch) -> extensions/$dest"

  git clone --depth 1 --branch "$branch" "$url" "$work"

  rm -rf "$target"
  mkdir -p "$target"
  cp -a "$work/." "$target/"
  rm -rf "$target/.git"

  # Provenance
  (cd "$work" && git rev-parse HEAD) > "$target/.upstream_commit"
  echo "$url" > "$target/.upstream_url"
  echo "$branch" > "$target/.upstream_branch"
}

post_process() {
  echo "==> Post-processing bundled extensions"

  local inx="$EXT_DIR/botbox3000/boxbot.inx"
  if [[ ! -f "$inx" ]]; then
    echo "ERROR: expected file not found: $inx"
    exit 1
  fi

  echo "Patching $inx"

  # Replace the FIRST <id> ... </id> block, regardless of whitespace/newlines inside.
  # (GNU sed on Debian supports the 0,ADDR form.)
  sed -i '0,/<id[[:space:]>]/{
/<id[[:space:]>]/,/<\/id>/c\
<id>org.knoxmakers.botbox</id>
}' "$inx"

  # Replace the FIRST <effectsmenu ...> ... </effectsmenu> block (handles attributes + multiline)
  sed -i '0,/<effectsmenu[^>]*>/{
/<effectsmenu[^>]*>/,/<\/effectsmenu>/c\
<effectsmenu>\
  <submenu _name="Knox Makers">\
    <submenu _name="Laser"/>\
  </submenu>\
</effectsmenu>
}' "$inx"
}


main() {
  # Sync phase
  for entry in "${REPOS[@]}"; do
    IFS='|' read -r name url branch dest <<<"$entry"
    sync_one "$name" "$url" "$branch" "$dest"
  done

  # Post-processing phase
  post_process

  # Commit phase
  cd "$ROOT"
  git add extensions

  if git diff --cached --quiet; then
    echo "No bundle changes."
    exit 0
  fi

  git commit -m "bundle: update ($(date -u +%Y-%m-%d))"
}

main "$@"

