cleanup-tmp.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env bash
  2. # cleanup-tmp.sh - Clean up old temporary files from .tmp directory
  3. set -euo pipefail
  4. # Defaults
  5. SESSION_DAYS=7
  6. TASK_DAYS=30
  7. EXTERNAL_DAYS=7
  8. FORCE=false
  9. # Parse arguments
  10. for arg in "$@"; do
  11. case "$arg" in
  12. --force) FORCE=true ;;
  13. --session-days=*) SESSION_DAYS="${arg#*=}" ;;
  14. --task-days=*) TASK_DAYS="${arg#*=}" ;;
  15. --external-days=*) EXTERNAL_DAYS="${arg#*=}" ;;
  16. esac
  17. done
  18. # Find old files
  19. SESSION_FILES=$(find .tmp/sessions -maxdepth 1 -mindepth 1 -type d -mtime +${SESSION_DAYS} 2>/dev/null || true)
  20. TASK_FILES=$(find .tmp/tasks -maxdepth 1 -mindepth 1 -type d -mtime +${TASK_DAYS} 2>/dev/null | while read d; do
  21. # Only include completed tasks (skip active ones)
  22. if [ -f "$d/task.json" ] && grep -q '"status": "completed"' "$d/task.json" 2>/dev/null; then
  23. echo "$d"
  24. fi
  25. done || true)
  26. EXTERNAL_FILES=$(find .tmp/external-context -maxdepth 1 -mindepth 1 -type d -mtime +${EXTERNAL_DAYS} 2>/dev/null || true)
  27. SESSION_COUNT=$(echo "$SESSION_FILES" | grep -c . 2>/dev/null || echo 0)
  28. TASK_COUNT=$(echo "$TASK_FILES" | grep -c . 2>/dev/null || echo 0)
  29. EXTERNAL_COUNT=$(echo "$EXTERNAL_FILES" | grep -c . 2>/dev/null || echo 0)
  30. TOTAL=$((SESSION_COUNT + TASK_COUNT + EXTERNAL_COUNT))
  31. if [ "$TOTAL" -eq 0 ]; then
  32. echo '{"status":"success","deleted":{"sessions":0,"tasks":0,"external":0},"freed_space":"0 B","summary":"No old temporary files found."}'
  33. exit 0
  34. fi
  35. # Show what will be deleted
  36. if [ "$FORCE" = false ]; then
  37. echo "Files to be deleted:"
  38. [ -n "$SESSION_FILES" ] && echo "$SESSION_FILES" | sed 's/^/ [session] /'
  39. [ -n "$TASK_FILES" ] && echo "$TASK_FILES" | sed 's/^/ [task] /'
  40. [ -n "$EXTERNAL_FILES" ] && echo "$EXTERNAL_FILES" | sed 's/^/ [external] /'
  41. echo ""
  42. read -r -p "Delete $TOTAL items? [y/N] " confirm
  43. [[ "$confirm" =~ ^[Yy]$ ]] || { echo "Cancelled."; exit 0; }
  44. fi
  45. # Delete
  46. [ -n "$SESSION_FILES" ] && echo "$SESSION_FILES" | xargs rm -rf
  47. [ -n "$TASK_FILES" ] && echo "$TASK_FILES" | xargs rm -rf
  48. [ -n "$EXTERNAL_FILES" ] && echo "$EXTERNAL_FILES" | xargs rm -rf
  49. echo "{\"status\":\"success\",\"deleted\":{\"sessions\":${SESSION_COUNT},\"tasks\":${TASK_COUNT},\"external\":${EXTERNAL_COUNT}},\"summary\":\"Cleaned up ${TOTAL} old temporary items.\"}"