#!/usr/bin/env bash
# gitploy — installe les sous-commandes « git deploy » / « git hotfix »
# pour le dépôt qui utilise cet outil, sans toucher au PATH.
#
# À lancer une fois (après un clone / init de submodule) :
#   gitploy/setup            (si monté en submodule sous gitploy/)
#   ./setup                  (si utilisé en dépôt autonome)
#
# git n'exécute jamais une config versionnée tout seul (sécurité) : cette
# étape unique est donc nécessaire.
set -euo pipefail

# Dossier réel de cet outil (résout aussi les symlinks éventuels).
SCRIPTS_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)

# Dépôt à configurer : le superprojet si on est un submodule, sinon le dépôt courant.
# On utilise les chemins rapportés par git (cohérents, insensibles aux symlinks).
SUPER=$(git -C "$SCRIPTS_DIR" rev-parse --show-superproject-working-tree 2>/dev/null || true)
if [ -n "$SUPER" ]; then
  TARGET="$SUPER"
  SUBTOP=$(git -C "$SCRIPTS_DIR" rev-parse --show-toplevel)
  REL="${SUBTOP#"$TARGET"/}"      # ex: gitploy
else
  TARGET=$(git -C "$SCRIPTS_DIR" rev-parse --show-toplevel)
  REL=""                          # outil à la racine du dépôt
fi

# Chemin de l'outil, portable, résolu au runtime via show-toplevel.
if [ -n "$REL" ]; then
  TOOLPATH="\$(git rev-parse --show-toplevel)/$REL"
else
  TOOLPATH="\$(git rev-parse --show-toplevel)"
fi

git -C "$TARGET" config alias.deploy "!\"$TOOLPATH/git-deploy\""
git -C "$TARGET" config alias.hotfix "!\"$TOOLPATH/git-hotfix\""

# Branche de dev par défaut si non définie.
git -C "$TARGET" config deploy.source >/dev/null 2>&1 || git -C "$TARGET" config deploy.source master

echo "✓ Alias installés sur : $TARGET"
echo "  git deploy / git hotfix   →  $REL/"
echo "  deploy.source = $(git -C "$TARGET" config deploy.source)"
echo "  deploy.push   = $(git -C "$TARGET" config --bool deploy.push 2>/dev/null || echo 'false (désactivé)')"
echo
echo "Complétion (optionnelle) — à ajouter à ~/.bashrc :"
echo "  source \"$SCRIPTS_DIR/deploy-completion.bash\""
echo
echo "Activer le push réel quand tu seras prêt :  git -C \"$TARGET\" config deploy.push true"
