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

# Migration en masse Fastmail -> Google Workspace, variante OAuth.
# Lit un CSV (dest_email,src_login,src_app_password), crée chaque compte via GAM
# si besoin, puis migre via imapsync (destination en XOAUTH2 service-account).
#
#   migrer-masse.sh                 migre tous les comptes du CSV
#   migrer-masse.sh --dry           test à blanc (passé à imapsync)
#   migrer-masse.sh --justlogin     teste seulement les connexions
#   migrer-masse.sh user@qlf.fr     ne traite que ce compte (utile pour relancer un échec)
#   migrer-masse.sh user@qlf.fr --dry
#
# Réglages surchargeables par variable d'environnement.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

CSV="${MIGRER_CSV:-migrations.csv}"
SRC_HOST="${SRC_HOST:-imap.fastmail.com}"
SRC_PORT="${SRC_PORT:-993}"
DST_HOST="${DST_HOST:-imap.gmail.com}"
DST_PORT="${DST_PORT:-993}"
SA_JSON="${SA_JSON:-$HOME/.gam/oauth2service.json}"
GAM_BIN="${GAM_BIN:-$HOME/bin/gam7/gam}"

CONF_DIR="${HOME}/.migrer"
LOG_DIR="${CONF_DIR}/logs"
CRED_FILE="${CRED_FILE:-$SCRIPT_DIR/comptes-crees.csv}"   # adresses + mots de passe temporaires
mkdir -p "$LOG_DIR"
[ -f "$CRED_FILE" ] || echo "email,mot_de_passe_temporaire" > "$CRED_FILE"
chmod 600 "$CRED_FILE"

# filtre optionnel sur un seul compte (1er arg s'il contient @)
ONLY=""
if [ "${1:-}" ] && [[ "$1" == *@* ]]; then ONLY="$1"; shift; fi
EXTRA=("$@")   # options transmises telles quelles à imapsync (--dry, --justlogin, ...)

[ -f "$CSV" ]     || { echo "CSV introuvable : $CSV" >&2; exit 1; }
[ -f "$SA_JSON" ] || { echo "Service account introuvable : $SA_JSON" >&2; exit 1; }
command -v imapsync >/dev/null || { echo "imapsync absent du PATH" >&2; exit 1; }

ok=(); ko=()

# saute l'en-tête, lit chaque ligne (process substitution : pas de sous-shell,
# les compteurs ok/ko survivent à la boucle)
while IFS=, read -r DEST SRC_LOGIN SRC_PASS; do
  DEST="$(echo "$DEST" | tr -d '\r' | xargs)"
  SRC_LOGIN="$(echo "$SRC_LOGIN" | tr -d '\r' | xargs)"
  SRC_PASS="$(echo "$SRC_PASS" | tr -d '\r' | xargs)"
  [ -z "$DEST" ] && continue
  [ -n "$ONLY" ] && [ "$DEST" != "$ONLY" ] && continue

  echo
  echo "==================================================================="
  echo ">>> $SRC_LOGIN  ->  $DEST"

  # 1. compte : créer si absent (prénom = partie locale, nom = domaine)
  if "$GAM_BIN" info user "$DEST" >/dev/null 2>&1; then
    echo "    compte déjà présent, pas de création"
  else
    local_part="${DEST%@*}" domain_part="${DEST#*@}"
    TEMP_PW="$(head -c 16 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | cut -c1-14)"
    echo "    création du compte (mot de passe temporaire, à changer au 1er login)..."
    if ! "$GAM_BIN" create user "$DEST" \
        firstname "$local_part" lastname "$domain_part" \
        password "$TEMP_PW" changepassword on; then
      echo "    ECHEC création $DEST" >&2
      ko+=("$DEST (création)"); continue
    fi
    echo "${DEST},${TEMP_PW}" >> "$CRED_FILE"
    sleep 10
  fi

  # 2. migration imapsync (destination en XOAUTH2, sans mot de passe)
  log="${DEST}_$(date +%Y%m%d_%H%M%S).log"
  if imapsync \
      --host1 "$SRC_HOST" --port1 "$SRC_PORT" --ssl1 \
      --user1 "$SRC_LOGIN" --password1 "$SRC_PASS" \
      --host2 "$DST_HOST" --port2 "$DST_PORT" --ssl2 \
      --user2 "$DEST" --password2 "$SA_JSON" --authmech2 XOAUTH2 \
      --automap --skipcrossduplicates \
      --logdir "$LOG_DIR" --logfile "$log" \
      ${EXTRA[@]+"${EXTRA[@]}"}; then
    echo "    OK ($log)"
    ok+=("$DEST")
  else
    echo "    ECHEC migration $DEST (voir $LOG_DIR/$log)" >&2
    ko+=("$DEST (migration)")
  fi
done < <(tail -n +2 "$CSV")

echo
echo "==================================================================="
echo "Réussis : ${#ok[@]}    Échecs : ${#ko[@]}"
[ "${#ko[@]}" -gt 0 ] && printf '  KO: %s\n' "${ko[@]}"
