(defpackage :dribble (:use :common-lisp :cl-irc)
            (:export :start-dribbler))
(in-package :dribble)

(defparameter *nickname* "onkobot")
(defparameter *server* "irc.at.freenode.net")
(defparameter *channel* "#dribblerbot")
(defparameter *real-name* "dribbler shows that (> CL Perl)")
(defparameter *user-name* "dribbler")

(defparameter *dribble-files*
  '("/home/asf/test_log"))

;;; You shouldn't need to edit below this line
;;; LINE

(defvar *connection*)

(defparameter *streams* nil)

(defun start-dribbler ()
  (setf *connection* (connect :nickname *nickname*
                              :server *server*
                              :username *user-name*
                              :realname *real-name*))
  (join *connection* *channel*)
  (loop for file in *dribble-files*
        do (let ((stream (open file :direction :input)))
             (push stream *streams*)
             (file-position stream :end)))
  (start-background-message-handler *connection*)
  (loop (unless (sb-sys:serve-all-events 1)
	  (mapc 'dribble-function *streams*))))

(defvar *last-message-times* (list 0 0 0))

(defun dribble-function (stream)
  (let ((line (read-line stream nil nil)))
    (when line
      (if (> (- (get-universal-time) (third *last-message-times*)) 10)
          (progn
            (privmsg *connection* *channel* line)
            (setf *last-message-times*
                  (cons (get-universal-time)
                        (nbutlast *last-message-times*))))
	  (progn
	    ;; seek to the end of the file; we drop all the lines in
	    ;; between, which might be suboptimal, but less suboptimal
	    ;; than flooding the channel with 411945 lines.
	    (let ((skipped-lines 0))
	    (loop while (read-line stream nil nil)
		  do (incf skipped-lines))
	    (privmsg *connection* *channel* (format nil "skipping ~A lines" skipped-lines))
	    (format *trace-output* "Yipes, skipping line ~S: too many messages in 10 seconds.~%" line)))))))