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

# ==============================================================================
# Setup remote machines: git aliases + zsh + Oh My Zsh
# Usage: ./scripts/setup-remote-machines.sh user@host1 user@host2 ...
# ==============================================================================

if [ $# -eq 0 ]; then
  echo "Usage: $0 user@host1 [user@host2 ...]"
  echo "Example: $0 matthieu@192.168.1.10 matthieu@192.168.1.20"
  exit 1
fi

REMOTE_SCRIPT='
set -e

echo "=== [1/3] Configuration git aliases ==="
git config --global alias.st "status"
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.ci "commit"
git config --global alias.cm "commit -m"
git config --global alias.s "status"
git config --global alias.last "log -1 HEAD"
git config --global alias.unstage "reset HEAD --"
git config --global alias.hist "log --oneline --graph --decorate --all"
git config --global alias.df "diff"
git config --global alias.dc "diff --cached"
git config --global alias.lg "log --oneline --graph --decorate"
git config --global alias.type "cat-file -t"
git config --global alias.dump "cat-file -p"
echo "  -> Git aliases OK"

echo "=== [2/3] Installation de zsh ==="
if command -v zsh &>/dev/null; then
  echo "  -> zsh deja installe ($(zsh --version))"
else
  if command -v apt-get &>/dev/null; then
    sudo apt-get update -qq && sudo apt-get install -y -qq zsh
  elif command -v dnf &>/dev/null; then
    sudo dnf install -y zsh
  elif command -v yum &>/dev/null; then
    sudo yum install -y zsh
  elif command -v pacman &>/dev/null; then
    sudo pacman -S --noconfirm zsh
  else
    echo "  !! Gestionnaire de paquets non reconnu, installe zsh manuellement"
    exit 1
  fi
  echo "  -> zsh installe"
fi

echo "=== [3/3] Installation de Oh My Zsh ==="
if [ -d "$HOME/.oh-my-zsh" ]; then
  echo "  -> Oh My Zsh deja installe"
else
  sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
  echo "  -> Oh My Zsh installe"
fi

echo "=== Terminé ! ==="
'

for HOST in "$@"; do
  echo ""
  echo "========================================"
  echo "  Configuration de: $HOST"
  echo "========================================"
  ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "$HOST" "$REMOTE_SCRIPT"

  # Extraire le user du format user@host
  REMOTE_USER="${HOST%%@*}"
  echo "  -> Changement du shell par defaut en zsh (necessite mot de passe sudo)..."
  ssh -t -o ConnectTimeout=10 "$HOST" "sudo chsh -s \$(which zsh) $REMOTE_USER"
  echo "  -> $HOST OK"
done

echo ""
echo "Toutes les machines ont ete configurees."
