#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH

;; incorporates RECENT into INDEX
;; USAGE aminet-incorporate-recent <host-spec>
;; e.g.: aminet-incorporate-recent ftp.luth.se:/pub/aminet
;; aminet-incorporate-recent <host-spec> file
;; only get readmes of files in file descs

(setq getit "/net/koala/bin/sh/getit")

(setq host-base (getn *arguments* 1))
(if (and host-base (/= #\/ (get host-base -1)))
  (put host-base -1 #\/)		;add trailing / to dir
)

(setq re-news (regcomp "^[a-zA-Z_0-9]"))
(setq readme-position 36)

(defun main ()
  (if (= 2 (length *arguments*))
    (incorporate-recent)
    (= 3 (length *arguments*)) 
    (get-readmes-from-file (getn *arguments* 2))

    t (progn
      (print-format "USAGE: aminet-incorporate-recent <host-spec>
as in: aminet-incorporate-recent ftp.luth.se:/pub/aminet\n")
      (exit 1)
    )
  )
  (exit)
)

(defun incorporate-recent ()
  (setq entries (list))
  (setq fd (open "INDEX"))
  (while (setq line (read-line fd ()))
    (if (regexec re-news line)
      (lappend entries line)
  ))
  (close fd)
  
  (setq fd (open "RECENT"))
  (setq news (list))
  (while (setq line (read-line fd ()))
    (if (regexec re-news line)
      (catch 'Found
	(dolist (entry entries) (if (= line entry) (throw 'Found)))
	(lappend news line)
	(write-line line)			;verbose: shows on stdout
    ))
  )
  (close fd)
  
  (setq entries (+ news entries))
  
  (with (fd (open "INDEX" :if-exists :supersede :direction :output))
    (dolist (entry entries)
      (write-line entry fd)
  ))

  (get-readmes news)
)

(defun get-readmes-from-file (file &aux
    (fd (open file))
    line
    (lines (list))
  )
  (while (setq line (read-line fd ())) 
    (if (regexec re-news line)
      (lappend lines line)
  ))
  (get-readmes lines)
)

(defun get-readmes (lines &aux 
    filename
    dir
    fd
    l
  )
  (dolist (line lines)
    (if (and (= (getn line readme-position) #\+) 
	(setq filename (match "^([^ ]+)[.][^. ]*[ ]" line 1))
	(setq filename (+ filename ".readme"))
	(setq dir (match "^[^ ]+[ ]+([^ ]+)" line 1))
      ) (progn
	(wait (system (list getit "-q" (+ host-base dir "/" filename))))
	(if (setq fd (open filename :error ())) (progn
	    (print-format "\n%0 %1:\n" 
	      (make-string (- 77 (length filename)) #\*) filename
	    )
	    (while (setq l (read-line fd ()))
	      (write-line l)
	    )
	    (setq fd ())
	  )
	  (print-format "##### file \"%0\" not found !!! #####\n" 
	    (+ dir "/" filename)
	))
	(wait (system (list "rm" "-f" filename)))
    ))
  )
  
)

(main)
