#!/bin/bash
# Grand Ménage : corbeille, caches, historique, cookies, journaux.
# Ne touche JAMAIS aux documents, photos, téléchargements ni applications.
# (c) TB INFORMATIQUE - Thierry Bonsigne - 06-42-29-28-18
OSA=/usr/bin/osascript
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
ICON="$RES/dialog-icon.png"
LOG="$HOME/Library/Logs/Grand-Menage.log"
CHROME_DIR="$HOME/Library/Application Support/Google/Chrome"
FX_PROFILES="$HOME/Library/Application Support/Firefox/Profiles"
SAFARI_DIR="$HOME/Library/Safari"
AS="/tmp/grand-menage-$$.scpt"
trap 'rm -f "$AS"' EXIT

# --- Petites fonctions utilitaires -----------------------------------------
libres_ko() { df -k / | awk 'NR==2 {print $4}'; }

en_mo() { awk -v k="$1" 'BEGIN{printf "%d", k/1024}'; }        # Ko -> Mo
en_go() { awk -v k="$1" 'BEGIN{printf "%.1f", k/1048576}'; }   # Ko -> Go

taille_de() {  # taille totale en Ko des chemins existants passés en argument
    local total=0 p s
    for p in "$@"; do
        [[ -e "$p" ]] || continue
        s=$(du -sk "$p" 2>/dev/null | awk '{print $1}')
        [[ "$s" =~ ^[0-9]+$ ]] && total=$((total + s))
    done
    echo "$total"
}

dialogue() {  # exécute le script AppleScript passé par heredoc, renvoie sa sortie
    cat > "$AS"
    $OSA "$AS" "$@"
}

# --- Écran d'accueil TB INFORMATIQUE ---------------------------------------
$OSA -e 'display dialog "© TB INFORMATIQUE" & return & "Thierry Bonsigne" & return & "Tél : 06-42-29-28-18" with title "Grand Ménage - TB INFORMATIQUE" buttons {"Continuer"} default button "Continuer" with icon note' >/dev/null

# --- Choix des éléments à nettoyer -----------------------------------------
CHOIX=$(dialogue "$ICON" <<'APPLESCRIPT'
on run argv
	set r to choose from list {"🗑️  Corbeille", "🧹  Caches du Mac", "🌐  Historique des navigateurs", "🍪  Cookies des navigateurs", "📄  Journaux système"} with prompt "Cochez ce que vous voulez nettoyer :" & return & return & "Vos documents, photos et applications ne sont jamais touchés." & return & "Les cookies supprimés déconnectent des sites (mots de passe à retaper)." with title "Grand Ménage - TB INFORMATIQUE" with multiple selections allowed and empty selection allowed
	if r is false then return ""
	set res to ""
	set n to count of r
	repeat with i from 1 to n
		set res to res & (item i of r)
		if i < n then set res to res & "|"
	end repeat
	return res
end run
APPLESCRIPT
) || exit 0
[[ -z "$CHOIX" ]] && exit 0

has_corbeille=0; has_caches=0; has_hist=0; has_cookies=0; has_logs=0
[[ "$CHOIX" == *"Corbeille"* ]]   && has_corbeille=1
[[ "$CHOIX" == *"Caches du Mac"* ]] && has_caches=1
[[ "$CHOIX" == *"Historique"* ]]  && has_hist=1
[[ "$CHOIX" == *"Cookies"* ]]     && has_cookies=1
[[ "$CHOIX" == *"Journaux"* ]]    && has_logs=1

# --- Navigateurs : à fermer avant historique / cookies ----------------------
if (( has_hist || has_cookies )); then
    OUVERTS=""
    pgrep -x Safari          >/dev/null 2>&1 && OUVERTS="Safari"
    pgrep -x "Google Chrome" >/dev/null 2>&1 && OUVERTS="${OUVERTS:+$OUVERTS, }Google Chrome"
    pgrep -x firefox         >/dev/null 2>&1 && OUVERTS="${OUVERTS:+$OUVERTS, }Firefox"
    if [[ -n "$OUVERTS" ]]; then
        REP=$(dialogue "$OUVERTS" "$ICON" <<'APPLESCRIPT'
on run argv
	set r to display dialog "Pour nettoyer l'historique et les cookies, les navigateurs doivent être fermés." & return & return & "Navigateurs ouverts : " & item 1 of argv & return & return & "Les fermer maintenant ? (pensez à sauvegarder vos pages ouvertes)" buttons {"Annuler", "Fermer les navigateurs"} default button "Fermer les navigateurs" with title "Grand Ménage" with icon (POSIX file (item 2 of argv))
	return button returned of r
end run
APPLESCRIPT
        ) || REP="Annuler"
        if [[ "$REP" == "Fermer les navigateurs" ]]; then
            $OSA -e 'tell application "Safari" to quit'        >/dev/null 2>&1
            $OSA -e 'tell application "Google Chrome" to quit' >/dev/null 2>&1
            $OSA -e 'tell application "Firefox" to quit'       >/dev/null 2>&1
            sleep 2
        else
            has_hist=0
            has_cookies=0
        fi
    fi
fi

if (( has_hist + has_corbeille + has_caches + has_cookies + has_logs == 0 )); then exit 0; fi

# --- Liste des fichiers visés (historique / cookies) ------------------------
HIST_FILES=()
COOK_FILES=()
while IFS= read -r f; do HIST_FILES+=("$f"); done < <(find "$CHROME_DIR" -maxdepth 2 -name 'History*' 2>/dev/null)
while IFS= read -r f; do HIST_FILES+=("$f"); done < <(find "$FX_PROFILES" -maxdepth 2 -name 'places.sqlite*' 2>/dev/null)
for f in "$SAFARI_DIR/History.db" "$SAFARI_DIR/History.db-shm" "$SAFARI_DIR/History.db-wal"; do
    [[ -e "$f" ]] && HIST_FILES+=("$f")
done
while IFS= read -r f; do COOK_FILES+=("$f"); done < <(find "$CHROME_DIR" -maxdepth 2 -name 'Cookies*' 2>/dev/null)
while IFS= read -r f; do COOK_FILES+=("$f"); done < <(find "$FX_PROFILES" -maxdepth 2 -name 'cookies.sqlite*' 2>/dev/null)
[[ -e "$SAFARI_DIR/Cookies.binarycookies" ]] && COOK_FILES+=("$SAFARI_DIR/Cookies.binarycookies")

# --- Tailles avant nettoyage ------------------------------------------------
LIBRE_AVANT=$(libres_ko)
t_corb=0; t_cache=0; t_hist=0; t_cook=0; t_logs=0
(( has_corbeille )) && t_corb=$(taille_de "$HOME/.Trash")
(( has_caches ))    && t_cache=$(taille_de "$HOME/Library/Caches")
(( has_hist ))      && t_hist=$(taille_de "${HIST_FILES[@]}")
(( has_cookies ))   && t_cook=$(taille_de "${COOK_FILES[@]}")
(( has_logs ))      && t_logs=$(taille_de "$HOME/Library/Logs")
TOTAL=$(( t_corb + t_cache + t_hist + t_cook + t_logs ))

if (( TOTAL == 0 )); then
    $OSA -e 'display dialog "Rien à nettoyer : tout est déjà propre ! ✨" buttons {"OK"} default button "OK" with title "Grand Ménage - TB INFORMATIQUE" with icon note' >/dev/null
    exit 0
fi

# --- Confirmation ------------------------------------------------------------
RESUME=""
(( has_corbeille )) && RESUME+="🗑️ Corbeille : $(en_mo "$t_corb") Mo"$'\n'
(( has_caches ))    && RESUME+="🧹 Caches : $(en_mo "$t_cache") Mo"$'\n'
(( has_hist ))      && RESUME+="🌐 Historique : $(en_mo "$t_hist") Mo"$'\n'
(( has_cookies ))   && RESUME+="🍪 Cookies : $(en_mo "$t_cook") Mo"$'\n'
(( has_logs ))      && RESUME+="📄 Journaux : $(en_mo "$t_logs") Mo"$'\n'
LIBRE_GO=$(en_go "$LIBRE_AVANT")

REP=$(dialogue "$RESUME" "$TOTAL" "$LIBRE_GO" "$ICON" <<'APPLESCRIPT'
on run argv
	set r to display dialog "Taille estimée : environ " & (item 2 of argv) & " Mo" & return & return & (item 1 of argv) & return & "Espace disque libre actuellement : " & (item 3 of argv) & " Go" & return & return & "Lancer le nettoyage ? (cela prend quelques secondes)" buttons {"Annuler", "🧹 Lancer le nettoyage"} default button "🧹 Lancer le nettoyage" with title "Grand Ménage - récapitulatif" with icon (POSIX file (item 4 of argv))
	return button returned of r
end run
APPLESCRIPT
) || exit 0
[[ "$REP" != "🧹 Lancer le nettoyage" ]] && exit 0

# --- Nettoyage ---------------------------------------------------------------
ERRS="/tmp/grand-menage-erreurs.txt"
: > "$ERRS"
RECAP=""

if (( has_corbeille )); then
    if find "$HOME/.Trash" -mindepth 1 -delete 2>>"$ERRS"; then
        RECAP+="🗑️ Corbeille vidée ✓"$'\n'
    else
        RECAP+="🗑️ Corbeille : certains éléments protégés restent (normal)."$'\n'
    fi
fi
if (( has_caches )); then
    find "$HOME/Library/Caches" -mindepth 1 -delete 2>>"$ERRS" && RECAP+="🧹 Caches nettoyés ✓"$'\n'
fi
if (( has_hist )); then
    for f in "${HIST_FILES[@]}"; do rm -f "$f" 2>>"$ERRS"; done
    RECAP+="🌐 Historique effacé ✓"$'\n'
fi
if (( has_cookies )); then
    for f in "${COOK_FILES[@]}"; do rm -f "$f" 2>>"$ERRS"; done
    RECAP+="🍪 Cookies effacés ✓"$'\n'
fi
if (( has_logs )); then
    find "$HOME/Library/Logs" -mindepth 1 ! -name 'Grand-Menage.log' -delete 2>>"$ERRS" && RECAP+="📄 Journaux nettoyés ✓"$'\n'
fi

LIBRE_APRES=$(libres_ko)
DIFF=$(( LIBRE_APRES - LIBRE_AVANT ))
(( DIFF < 0 )) && DIFF=$TOTAL
DIFF_MO=$(en_mo "$DIFF")

# --- Note sur les dossiers protégés par macOS --------------------------------
NOTE=""
if grep -q "Operation not permitted" "$ERRS" 2>/dev/null; then
    NOTE=$'\n'"ℹ️ Safari protège ses données : pour l'inclure, ouvrez Réglages Système → Confidentialité → Accès intégral au disque et autorisez Grand Ménage."
fi

# --- Récapitulatif final -----------------------------------------------------
dialogue "$RECAP" "$DIFF_MO" "$(en_go "$LIBRE_APRES")" "$NOTE" "$ICON" <<'APPLESCRIPT'
on run argv
	display dialog "✅ Grand Ménage terminé !" & return & return & (item 1 of argv) & return & "Espace libéré : environ " & (item 2 of argv) & " Mo" & return & "Espace disque libre : " & (item 3 of argv) & " Go" & (item 4 of argv) buttons {"OK"} default button "OK" with title "Grand Ménage - TB INFORMATIQUE" with icon (POSIX file (item 5 of argv))
end run
APPLESCRIPT

mkdir -p "$(dirname "$LOG")"
echo "$(date '+%d/%m/%Y %H:%M') | corbeille=$has_corbeille caches=$has_caches hist=$has_hist cookies=$has_cookies logs=$has_logs | libéré ≈ ${DIFF_MO} Mo" >> "$LOG"
exit 0
