#lang scheme/base

;; The planet paths for your teachpacks (the part after the last "/" will be
;; used for the teachpack filename); this is the only thing that you need to
;; modify in this file.  You can have versions in this path.
(define teachpacks '(eli/sample-teachpacks/flip eli/sample-teachpacks/rand))

(require scheme/list scheme/string scheme/file)

(provide post-installer)
(define (post-installer plt-home)
  (define skipped-tps '())
  (define tp-dir (build-path (find-system-path 'addon-dir)
                             (version) "collects" "installed-teachpacks"))
  (for ([tp teachpacks])
    (define name (symbol->string tp))
    (define tp-name
      (cond [(regexp-match #rx"^.*/([^/.]+)$" name) => cadr]
            [else (error 'post-installer "bad teachpack spec: ~e" tp)]))
    (define tp-file (string-append tp-name ".ss"))
    (define tp-path (build-path tp-dir tp-file))
    (define header-line (format ";; a stub teachpack file for ~a\n" name))
    (define existing
      (and (file-exists? tp-path)
           (with-input-from-file tp-path
             (lambda () (read-string (string-length header-line))))))
    (make-directory* tp-dir)
    (if (or (not existing) (equal? header-line existing))
      ;; the file is not there, or it is and it's ours, write it (even if it's
      ;; there, because we might want to update the, eg -- different version)
      (with-output-to-file tp-path #:exists 'truncate
        (lambda ()
          (printf "~a#lang scheme/base\n~
                   (require (planet ~s))\n~
                   (provide (all-from-out (planet ~s)))\n"
                  header-line tp tp)))
      ;; the file is there, but has different contents
      (set! skipped-tps (cons tp-file skipped-tps))))
  (unless (null? skipped-tps)
    (error 'teachpacks-installation
           "the following teachpack(s) were not installed because there were ~
            already files by the same name at ~a: ~a"
           tp-dir (string-append* (add-between skipped-tps ", ")))))