#!/usr/bin/env bash
# Revision: 2
# Bumps REVISION at repo root and updates the "Revision: N" line in all tracked files.
# Run from repo root, or use with: ./emmc-provisioning/scripts/bump-revision.sh
# Optional: use in a pre-commit hook so every commit gets a new revision.

set -e
# Script lives in emmc-provisioning/scripts/; repo root is two levels up
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
REVISION_FILE="$ROOT/REVISION"

# Files to update (relative to ROOT). Each must contain a line matching:
#   # Revision: N   or   <!-- Revision: N -->
TRACKED=(
  emmc-provisioning/scripts/bump-revision.sh
  emmc-provisioning/scripts/pre-commit-revision.sh
  emmc-provisioning/host/build-cloudinit-image.sh
  emmc-provisioning/host/flash-emmc-on-connect.sh
  emmc-provisioning/host/run-shrink-on-host.sh
  emmc-provisioning/host/README.md
  emmc-provisioning/host/cm4-flash-trigger.sh
  emmc-provisioning/dashboard/app.py
  emmc-provisioning/dashboard/templates/index.html
  emmc-provisioning/dashboard/templates/home.html
  emmc-provisioning/dashboard/templates/cloudinit_build.html
  emmc-provisioning/dashboard/templates/admin.html
  emmc-provisioning/dashboard/templates/login.html
  emmc-provisioning/dashboard/templates/portal_files.html
  emmc-provisioning/cloud-init/first-boot.sh
  emmc-provisioning/cloud-init/first-boot.conf
  emmc-provisioning/cloud-init/fileserver/start-chromium.sh
  emmc-provisioning/cloud-init/fileserver/01-set-rotation-once.sh
  emmc-provisioning/cloud-init/fileserver/02-set-wallpaper-once.sh
  emmc-provisioning/cloud-init/fileserver/set-rotation-at-login.sh
  emmc-provisioning/cloud-init/fileserver/five-tap-close-chromium.py
  emmc-provisioning/scripts/deploy-to-proxmox.sh
  emmc-provisioning/scripts/deploy-dashboard-to-lxc.sh
  emmc-provisioning/scripts/sync-portal-files-to-lxc.sh
  README.md
  emmc-provisioning/README.md
)

current=1
[[ -f "$REVISION_FILE" ]] && current=$(awk '/^[0-9]+$/ { print $1; exit }' "$REVISION_FILE" || true)
[[ -z "$current" ]] && current=0
next=$((current + 1))
echo "$next" > "$REVISION_FILE"

for rel in "${TRACKED[@]}"; do
  f="$ROOT/$rel"
  [[ "$rel" == "REVISION" ]] && continue
  [[ ! -f "$f" ]] && continue
  if grep -qE 'Revision: [0-9]+|<!-- Revision: [0-9]+ -->' "$f" 2>/dev/null; then
    sed -i -E 's/(Revision: )[0-9]+/\1'"$next"'/; s/(<!-- Revision: )[0-9]+( -->)/\1'"$next"'\2/' "$f"
  fi
done

echo "Revision bumped to $next"
