#!/bin/bash
# clean-mini.sh — range le bordel de dev sur le Mac mini + passage auto chaque soir.
# Sélectif et conservateur : ne supprime QUE du régénérable (caches, node_modules
# de vieux dépôts, .DS_Store, DerivedData périmés). Le reste = rapport, pas gachette.
# install : curl -fsSL http://77.42.67.118:6080/clean-mini.sh | bash
set -u
SERVEUR="77.42.67.118"
LOG="$HOME/Library/Logs/clean-mini.log"
mkdir -p "$(dirname "$LOG")"

AVANT=$(df -k / | awk 'NR==2{print $4}')
log() { echo "$(date '+%F %H:%M') $*" | tee -a "$LOG"; }

# dossiers dev candidats (le gros bordel connu : ~/Desktop/DEV/SAAS)
DEVS=""
for d in "$HOME/Desktop/DEV" "$HOME/DEV" "$HOME/dev" "$HOME/src"; do
  [ -d "$d" ] && DEVS="$DEVS|$d"
done

# 1) node_modules des dépôts sans activité depuis 60+ jours (regenerables via npm)
IFS='|'
for DEV in $DEVS; do
  [ -z "$DEV" ] && continue
  find "$DEV" -maxdepth 5 -type d -name node_modules 2>/dev/null | while IFS= read -r NM; do
    REPO=$(dirname "$NM")
    GITDIR="$REPO/.git"
    [ -d "$GITDIR" ] || continue
    AGE=$(( ( $(date +%s) - $(stat -f %m "$GITDIR") ) / 86400 ))
    if [ "$AGE" -gt 60 ]; then
      TAILLE=$(du -sk "$NM" 2>/dev/null | awk '{print $1}')
      rm -rf "$NM"
      log "node_modules >60j supprime : $REPO ($((TAILLE/1024)) Mo)"
    fi
  done
done
unset IFS

# 2) .DS_Store et debris dans les dossiers dev
for DEV in $(echo "$DEVS" | tr '|' ' '); do
  find "$DEV" -name '.DS_Store' -type f -delete 2>/dev/null
done

# 3) caches regénérables (Xcode, npm, pip, brew) — que les vieux
find "$HOME/Library/Developer/Xcode/DerivedData" -maxdepth 1 -mindepth 1 -mtime +30 -exec rm -rf {} + 2>/dev/null
[ -d "$HOME/Library/Developer/CoreSimulator/Caches" ] && find "$HOME/Library/Developer/CoreSimulator/Caches" -maxdepth 1 -mindepth 1 -mtime +30 -exec rm -rf {} + 2>/dev/null
[ -d "$HOME/Library/Caches/pip" ] && find "$HOME/Library/Caches/pip" -maxdepth 1 -mindepth 1 -mtime +30 -exec rm -rf {} + 2>/dev/null
command -v npm >/dev/null && npm cache clean --force >/dev/null 2>&1
command -v brew >/dev/null && brew cleanup -s >/dev/null 2>&1

# 4) rapport : les 12 plus gros trucs qui restent sous DEV
log "--- rapport taille (top 12 sous dossiers dev) ---"
for DEV in $(echo "$DEVS" | tr '|' ' '); do
  du -sk "$DEV" 2>/dev/null | while IFS= read -r line; do log "TOTAL $DEV = $(( $(echo "$line" | awk '{print $1}') / 1024 )) Mo"; done
  find "$DEV" -maxdepth 3 -mindepth 1 -type d 2>/dev/null | while IFS= read -r d2; do du -sk "$d2" 2>/dev/null; done | sort -rn | head -12 | while IFS= read -r l; do log "  $(( $(echo "$l" | awk '{print $1}') / 1024 )) Mo  $(echo "$l" | cut -f2-)"; done
done

APRES=$(df -k / | awk 'NR==2{print $4}')
log "libere : $(( (AVANT - APRES) / 1024 )) Mo"

# 5) job nocturne launchd (23h30) — idempotent
PLIST="$HOME/Library/LaunchAgents/com.sheriff.clean-mini.plist"
cat > "$PLIST" <<PLIST_EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>com.sheriff.clean-mini</string>
  <key>ProgramArguments</key><array>
    <string>/bin/bash</string><string>-c</string><string>curl -fsSL http://$SERVEUR:6080/clean-mini.sh | /bin/bash -s -- --nightly</string>
  </array>
  <key>StartCalendarInterval</key><dict><key>Hour</key><integer>23</integer><key>Minute</key><integer>30</integer></dict>
  <key>StandardOutPath</key><string>$LOG</string>
</dict></plist>
PLIST_EOF
launchctl unload "$PLIST" 2>/dev/null
launchctl load "$PLIST" 2>/dev/null
log "OK — nettoyage installe, repassera chaque soir a 23h30 (log: $LOG)"
echo
echo "=================================================================="
echo " Menage termine. Rapport complet : $LOG"
echo " Passage automatique chaque soir a 23h30 (launchd, 0 cout IA)."
echo "=================================================================="