#!/usr/bin/env -S sbcl --script

(defun get-stored-count (file)
  (if (probe-file file)
      (with-open-file (stream file :direction :input :if-does-not-exist nil)
        (let ((val (read stream nil nil)))
          (if (numberp val) val 0)))
      0))

(defun save-stored-count (file count)
  (with-open-file (stream file :direction :output :if-exists :supersede :if-does-not-exist :create)
    (format stream "~A" count)))

;; Enforce an absolute path relative to your home folder so CGI doesn't lose track of it
(let* ((user (sb-ext:posix-getenv "USER"))
       (file (format nil "/home/~A/public_html/count-data.txt" user))
       (query-string (sb-ext:posix-getenv "QUERY_STRING"))
       (current-count (get-stored-count file)))
  
  ;; Output the structural HTTP Status and Content-Type first to stop the server crash
  (format t "Status: 200 OK~%")
  (format t "Content-Type: text/plain; charset=utf-8~%~%")
  
  ;; Process count logic
  (if (and query-string (search "ignore=true" query-string))
      (format t "~A" current-count)
      (let ((new-count (1+ current-count)))
        (save-stored-count file new-count)
        (format t "~A" new-count))))
