#!/bin/bash
echo "########## ACTIONS $(date) ##########"
BK=~/.maintenance-logs/backups-cluster128-20260712
DEL=~/_supprimes_20260712
mkdir -p "$BK" "$DEL"

echo "############ A. s-hombrouck : reprise admin (email + mot de passe) ############"
NEWMAIL="kevin.saillard@gmail.com"
NEWPASS=$(openssl rand -hex 12)
php ~/_shombrouck_fix.php "$NEWMAIL" "$NEWPASS"
echo "  >>> IDENTIFIANTS s-hombrouck : email=$NEWMAIL   mot_de_passe=$NEWPASS"

echo "############ B. amar : suppression (sauvegarde -> drop tables -> retrait dossier) ############"
if [ -f ~/amar/wp-config.php ]; then
  IFS=$'\t' read -r DBN DBU DBP DBH DBPT < <(php ~/_creds.php amar)
  TABLES=$(php ~/_amar_tables.php list)
  echo "  base=$DBN  tables=[$TABLES]"
  if [ -n "$DBN" ] && [ -n "$TABLES" ]; then
    CNF=$(mktemp)
    printf '[client]\nuser=%s\npassword=%s\nhost=%s\nport=%s\n' "$DBU" "$DBP" "$DBH" "$DBPT" > "$CNF"
    if mysqldump --defaults-extra-file="$CNF" --no-tablespaces --single-transaction "$DBN" $TABLES > "$BK/amar-tables-DELETED.sql" 2>"$BK/amar-dump.err"; then
      echo "  sauvegarde OK ($(wc -c <"$BK/amar-tables-DELETED.sql") o) -> $BK/amar-tables-DELETED.sql"
      php ~/_amar_tables.php drop
    else
      echo "  sauvegarde ECHEC ($(head -1 "$BK/amar-dump.err")) -> DROP ANNULE (tables conservees)"
    fi
    rm -f "$CNF"
  else
    echo "  creds/tables amar KO -> DB non touchee"
  fi
  mv ~/amar "$DEL/amar" && echo "  dossier ~/amar -> $DEL/amar (reversible)"
else
  echo "  ~/amar/wp-config.php absent -> deja retire ?"
fi
echo "########## FIN ACTIONS $(date) ##########"
