;;; jao-dirmon.el --- little utility to monitor disk usage  -*- lexical-binding: t; -*-

;; Copyright (C) 2022, 2024, 2025  jao

;; Author: jao <mail@jao.io>
;; Keywords: tools

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; What directories suddenly increased their size?

;;; Code:

(require 'multisession)
(require 'view)
(require 'jao-shell)

(define-multisession-variable jao-dirmon-last '())

(defvar jao-dirmon-roots '("/var/local" "~"))

(defun jao-dirmon-dirs ()
  (mapcan (lambda (d)
            (jao-shell-cmd-lines
             (format "find %s -mindepth 2 -maxdepth 3 -type d" d)))
          jao-dirmon-roots))

(defun jao-dirmon-sizes ()
  (mapcar (lambda (f)
            (let ((x (split-string (jao-shell-string "du -BM -s" f))))
              (cons (cadr x) (string-to-number (car x)))))
          (jao-dirmon-dirs)))

(defvar jao-dirmon-threshold 100)
(defvar jao-dirmon-last-delta nil)
(defvar jao-dirmon-buffer "*jao-dirmon")

(defun jao-dirmon--show-deltas (old current deltas)
  (with-current-buffer (get-buffer-create jao-dirmon-buffer)
    (view-mode-disable)
    (delete-region (point-min) (point-max))
    (insert "High deltas since " (car old) "\n\n")
    (dolist (d (seq-sort-by #'cdr #'> deltas))
      (insert (format "- %s: %s Mb\n" (car d) (cdr d))))
    (insert "\n\nSizeable dirs\n\n")
    (let ((threshold (* 10 jao-dirmon-threshold)))
      (dolist (c (seq-take-while (lambda (x) (> (cdr x) threshold))
                                 (seq-sort-by #'cdr #'> current)))
        (insert (format "- %s: %s Mb\n" (car c) (cdr c)))))
    (beginning-of-buffer)
    (view-mode-enable)
    (pop-to-buffer (current-buffer) nil t)
    (when (y-or-n-p "Save current state?")
      (setf (multisession-value jao-dirmon-last)
            (cons (current-time-string) current)))))

;;;###autoload
(defun jao-dirmon-report ()
  (interactive)
  (let ((old (multisession-value jao-dirmon-last))
        (current (jao-dirmon-sizes))
        (high ()))
    (dolist (c current)
      (let ((d (- (cdr c) (alist-get (car c) old 0 nil #'string=))))
        (when (> (abs d) jao-dirmon-threshold)
          (push (cons (car c) d) high))))
    (setq jao-dirmon-last-delta high)
    (jao-dirmon--show-deltas old current jao-dirmon-last-delta)
    jao-dirmon-last-delta))

(provide 'jao-dirmon)
;;; jao-dirmon.el ends here
