#!/bin/bash
# LXC Arch Container Cleanup Script
# Usage: sudo bash cleanup.sh [--auto]

set -euo pipefail

AUTO=0
if [[ "${1:-}" == "--auto" ]]; then
  AUTO=1
fi

ask() {
  if [[ $AUTO -eq 1 ]]; then
    return 0
  fi
  read -rp "$1 [y/N]: " ans
  [[ "$ans" =~ ^[Yy]$ ]]
}

# --- PRE-CHECK ---
echo "=== Disk Usage (Before) ==="
df -h /
echo ""

# 1. PACMAN / PARU CACHE
if ask "Clean pacman package cache (keeps only latest 2 versions)?"; then
  if command -v paccache &>/dev/null; then
    paccache -rk2
  else
    echo "Installing pacman-contrib for paccache..."
    pacman -S --noconfirm pacman-contrib
    paccache -rk2
  fi
fi

# 2. ORPHANED PACKAGES (pacman/paru)
echo ""
echo ">>> Checking for orphaned packages..."
orphans=$(pacman -Qdtq 2>/dev/null || true)
if [[ -n "$orphans" ]]; then
  echo "Orphans found:"
  echo "$orphans"
  if ask "Remove orphaned packages?"; then
    # shellcheck disable=SC2086
    pacman -Rns --noconfirm $orphans
  fi
else
  echo "No orphaned packages found."
fi

# 3. PARU BUILD CACHE (AUR)
if command -v paru &>/dev/null; then
  echo ""
  if ask "Clean paru build cache (~/.cache/paru)?"; then
    CACHE_DIR="${HOME}/.cache/paru"
    if [[ -d "$CACHE_DIR" ]]; then
      rm -rf "$CACHE_DIR/clone"/* 2>/dev/null || true
      rm -rf "$CACHE_DIR/diffs"/* 2>/dev/null || true
      echo "Paru cache cleaned."
    fi
  fi
fi

# 4. PODMAN CLEANUP
if command -v podman &>/dev/null; then
  echo ""
  echo ">>> Podman cleanup..."

  dangling=$(podman images -f dangling=true -q 2>/dev/null || true)
  if [[ -n "$dangling" ]]; then
    echo "Dangling images found."
    if ask "Remove dangling podman images?"; then
      podman image prune -f
    fi
  else
    echo "No dangling podman images."
  fi

  if ask "Run full podman system prune (removes unused containers, networks, images)?"; then
    podman system prune -f
  fi
else
  echo "Podman not installed, skipping."
fi

# 5. JOURNAL LOGS
if ask "Vacuum systemd journal to 7 days / 100MB?"; then
  journalctl --vacuum-time=7d --vacuum-size=100M
fi

# 6. TEMP FILES
if ask "Clean /tmp and /var/tmp (files older than 3/7 days)?"; then
  find /tmp -type f -atime +3 -delete 2>/dev/null || true
  find /var/tmp -type f -atime +7 -delete 2>/dev/null || true
  echo "Temp files cleaned."
fi

# 7. TRIM (helpful on SSD/thin-provisioned storage)
if command -v fstrim &>/dev/null; then
  if ask "Run fstrim to discard unused blocks?"; then
    fstrim -av / 2>/dev/null || echo "fstrim failed or not supported by host storage"
  fi
fi

# 8. LARGE LOG CHECK
echo ""
echo ">>> Large log files (>10MB) in /var/log:"
find /var/log -type f -size +10M -exec ls -lh {} + 2>/dev/null || true

echo ""
echo "=== Disk Usage (After) ==="
df -h /
