#!/bin/sh
# Backup de la prod Perlette avant MEP. Rejouable : chaque execution cree un
# horodatage distinct, rien n'est ecrase.
#
# Perimetre : la base complete + tout ce que la MEP touche (core, thème, plugins,
# mu-plugins, .htaccess). Les uploads (598 Mo) sont EXCLUS : ni le deploiement FTP
# ni la mise a jour du core n'y ecrivent, et ils resteraient identiques.
set -e

WP=~/dev
DEST=~/backups
STAMP=$(date +%Y%m%d-%H%M%S)

mkdir -p "$DEST"
chmod 700 "$DEST"
# Ceinture et bretelles : le docroot est ~/dev, donc ~/backups est deja hors web.
printf 'Require all denied\n' > "$DEST/.htaccess" 2>/dev/null || true

echo "== 1/3  Dump de la base"
~/bin/wp db export "$DEST/db-$STAMP.sql" --path="$WP" --add-drop-table 2>/dev/null
gzip -f "$DEST/db-$STAMP.sql"
ls -lh "$DEST/db-$STAMP.sql.gz"

echo "== 2/3  Archive des fichiers (hors uploads)"
tar czf "$DEST/files-$STAMP.tar.gz" \
  -C "$WP" \
  --exclude='wp-content/uploads' \
  --exclude='wp-content/cache' \
  wp-admin wp-includes wp-content .htaccess wp-config.php index.php 2>/dev/null
ls -lh "$DEST/files-$STAMP.tar.gz"

echo "== 3/3  Etat des lieux (pour comparaison apres MEP)"
{
  echo "# Backup $STAMP"
  ~/bin/wp core version --path="$WP" 2>/dev/null
  ~/bin/wp plugin list --fields=name,status,version --format=csv --path="$WP" 2>/dev/null
} > "$DEST/etat-$STAMP.txt"
cat "$DEST/etat-$STAMP.txt"

echo
echo "TERMINE. Restauration :"
echo "  base    : ~/bin/wp db import $DEST/db-$STAMP.sql --path=$WP  (apres gunzip)"
echo "  fichiers: tar xzf $DEST/files-$STAMP.tar.gz -C $WP"
