#!/bin/sh
# -----------------------------------------------------------------------------
# ObsiGate — rattache l'incrément de version au commit qui vient d'être créé,
# puis crée le tag `vX.Y.Z` de la version livrée.
#
# Deux situations :
#   1. `prepare-commit-msg` a incrémenté ./VERSION et mis à jour les fichiers
#      dérivés (package.json, desktop, READMEs, ROADMAP, CHANGELOG) : on les
#      rattache ici au commit via `--amend` (le commit n'est pas encore poussé) ;
#   2. le message venait d'un éditeur : l'incrément a été différé, il est
#      calculé ici à partir du message final (`COMMIT_EDITMSG`).
#
# Résultat : la version livrée, le contenu du commit et le tag correspondent
# toujours. Le tag est publié avec la branche à chaque push (`push.followTags`,
# posé par scripts/install-hooks.sh).
# -----------------------------------------------------------------------------
set -eu

[ "${SKIP_VERSION_BUMP:-}" = "" ] || exit 0
[ "${OBSIGATE_VERSION_AMENDING:-}" = "" ] || exit 0   # garde anti-récursion

root="$(git rev-parse --show-toplevel)"
version_file="$root/VERSION"
[ -f "$version_file" ] || exit 0

# Opérations en cours (rebase, merge, cherry-pick…) : ne jamais amender ici.
for state in rebase-merge rebase-apply CHERRY_PICK_HEAD REVERT_HEAD MERGE_HEAD BISECT_LOG; do
  if [ -e "$(git rev-parse --git-path "$state")" ]; then
    exit 0
  fi
done

list="$(git rev-parse --git-path obsigate-version-files)"
defer="$(git rev-parse --git-path obsigate-version-defer)"

# Cas 2 : l'incrément avait été différé (commit rédigé dans un éditeur).
if [ -f "$defer" ]; then
  rm -f "$defer"
  rm -f "$list"
  tool="$root/scripts/bump_version.py"
  py=""
  for cand in python3 python; do
    if command -v "$cand" >/dev/null 2>&1; then py="$cand"; break; fi
  done
  if [ -n "$py" ] && [ -f "$tool" ]; then
    "$py" "$tool" --from-message-file "$(git rev-parse --git-path COMMIT_EDITMSG)" \
          --files-out "$list" || true
  fi
fi

# Rattachement des fichiers synchronisés au commit qui vient d'être créé.
if [ -s "$list" ]; then
  # shellcheck disable=SC2046
  git add -- $(tr -d '\r' < "$list")
  OBSIGATE_VERSION_AMENDING=1 \
    git commit --amend --no-edit --no-verify --quiet
  rm -f "$list"
fi

ver="$(tr -d ' \t\r\n' < "$version_file")"
[ -n "$ver" ] || exit 0

if git rev-parse -q --verify "refs/tags/v$ver" >/dev/null 2>&1; then
  exit 0
fi

git tag -a "v$ver" -m "ObsiGate v$ver"
echo "ObsiGate version : tag v$ver créé (poussé avec la branche)."
