#!/usr/local/bin/clisp
;
; Tracking Server (started via inetd)
; Simple Grid Protocol 1.04 - Copyright (c) Brendan Kosowski 2004, 2005, 2015
;
(defvar token)
(defvar lin)
(defvar ip)
(defvar acr)
(defvar flags)
(defvar fr)
(defvar fw)
(defvar fl)
(defvar all)

(defun gridlock ()
	(loop
		(setq fl (open "/home/grid/grid.lock" :direction :output :if-exists nil))
		(when fl (return))
	)
	(close fl)
)

(defun gridunlock ()
	(delete-file "/home/grid/grid.lock")
)

(defun purge-old ()

	(gridlock)

	(setq fr (open "/home/grid/grid.dat" :direction :input))
	(setq all (read fr))
	(close fr)

	(setq all (remove (- (get-universal-time) 40) all :test #'> :key #'third))

	(setq fw (open "/home/grid/grid.dat" :direction :output))
	(prin1 all fw)
	(close fw)

	(gridunlock)
)

(format t "Simple Grid Protocol 1.04 - Copyright (c) Brendan Kosowski 2004, 2005, 2015~%")

(setq fr (open "/home/grid/token.dat" :direction :input))
(setq token (read-line fr))
(close fr)

(format t "token?~%")
(when (string= token (read-line))

	(loop

		(format t "what?~%")
		(setq lin (read-line))
		(purge-old)

		(when (string= lin "help")
			(format t "commands: help bye quit join show~%")
		)

		(when (string= lin "bye")
			(return)
		)

		(when (string= lin "quit")
			(return)
		)

		(when (string= lin "join")

			(format t "ip?~%")
			(setq ip (read-line))
			(format t "acr?~%")
			(setq acr (floor (read)))
			(format t "flags?~%")
			(setq flags (read-from-string (read-line)))

			(gridlock)

			(setq fr (open "/home/grid/grid.dat" :direction :input))
			(setq all (read fr))
			(close fr)

			(setq all (remove ip all :test #'string-equal :key #'first))
			(push (list ip acr (get-universal-time) flags) all)

			(setq fw (open "/home/grid/grid.dat" :direction :output))
			(prin1 all fw)
			(close fw)

			(gridunlock)
		)

		(when (string= lin "show")

			(gridlock)

			(setq fr (open "/home/grid/grid.dat" :direction :input))
			(setq all (read fr))
			(close fr)

			(gridunlock)

			(setq all (sort all #'> :key #'second))
			(prin1 all)
			(format t "~%")
		)
	)
)
