#!/usr/bin/env -S sbcl --script
(require "uiop")
(load "/home/chris/.sbclrc")
(ql:quickload :serapeum)

(defun get-value (file)
  "Read a file and get it's value as a string"
  (serapeum:trim-whitespace (uiop:read-file-string file)))

(defun close-eww ()
  (run-program "eww" '("close" "battery") :search "/run/current-system/sw/bin/"))
(defun open-eww ()
  (run-program "eww" '("open" "battery") :search "/run/current-system/sw/bin/"))

(defun clear-file (file)
  (with-open-file (out file :direction :output :if-exists :supersede)
    (write-sequence "      " out))
  (format t "~&Clearing killed"))

(defun main ()
  (loop do (let ((capacity (parse-integer
                            (get-value "/sys/class/power_supply/BAT1/capacity")
                            :junk-allowed t))
                 (status (get-value "/sys/class/power_supply/BAT1/status")))
             (format t "~&Charge: ~a, Status: ~a" capacity status)
             (if (string= "Charging" status)
                 (progn
                   (format t "~&Charging, closing EWW")
                   (close-eww))
                 (if (<= capacity 30)
                     (let ((killed (get-value "/tmp/ewwbattery")))
                       (if (string= "killed" killed)
                           (progn
                             (format t "~&EWW has been killed, waiting 3 minutes")
                             (clear-file #p"/tmp/ewwbattery")
                             (sleep 350)))
                          (format t "~&Opening EWW")
                          (open-eww))
                     (progn (format t "~&Charged more than 30%, Closing EWW")
                            (clear-file #p"/tmp/ewwbattery")
                            (close-eww))))
             (sleep 10))))

(main)