;; mail-stack-dump-on-error-to
;;AUTOLOAD: mail-stack-dump-on-error-to
;;AUTODOC: mail-stack-dump-on-error-to "error handler sending a whole dump by email to maintainer"
;; (mail-stack-dump-on-error-to user adress [N] [forms...])
;;
;;dumps as much info it can on the running process and sends it to the user, 
;;then exit with error code N (default 1) when an error arrives
;;executes the code in forms before dumping and exiting. Code in forms
;;can clean things up or set global variables to values so that they will be 
;;included in the mail to user at adress

(defvar mail-stack-dump-on-error-to:old ())

(defun mail-stack-dump-on-error-to (adress &optional (exit-after 1) &rest forms)
  (setq mail-stack-dump-on-error-to:old *error-handlers*)
  (setq print-stack-dump:max-level *maxint*)
  (setq mail-stack-dump-on-error-to:exit-after exit-after)
  (setq *error-handlers* (list (mail-whole-stack-dump adress exit-after forms)))
)

(defmacro mail-whole-stack-dump (adress exit-after forms &aux
    fd
  )
  '(eval (backquote (lambda (&rest mail-whole-stack-dump:args &aux fd)
    (apply progn ',forms)
    (system (print-format String 
	"mail -s \"Stack dump of klone script %0\" %1" (getn *arguments* 0)
	,adress
      )
      :input 'fd)
    (with (print-stack-dump:output fd
	print-stack-dump:exit-after ,exit-after
      )
      (apply print-whole-stack-dump mail-whole-stack-dump:args)
)))))
