generate.rkt
#lang racket/base

(require (prefix-in main: "main.rkt")
         (only-in (planet synx/maker:1) depending-on)
         srfi/8
         racket/cmdline 
         racket/file
         racket/system
         unstable/pretty)

(define (open-output-nowhere)
  (define-values (input output) (make-pipe))
  (thread
   (λ ()
     (define buf (make-bytes 1024))
     (let loop ()
       (when (not (eof-object? (read-bytes! buf input)))
         (loop)))))
  output)

(define (generate filename)
 (let ((filename (build-path (current-directory) filename)))
   (receive (base name is-dir?) (split-path filename)
            (let* ((temp (build-path base "compiled"))
                   (dest (build-path temp name))
                   (exe (build-path base (regexp-replace #rx"\\.[^\\.]*" (path->string name) "")))
                   (this-mod (string->symbol (string-append (path->string name) "-exe")))
                   (that-mod (path->string (build-path 'up name))))
              (depending-on 
               temp '()
               (λ (dir blah)
                 (make-directory* dir)))
              (depending-on 
               dest '()
               (λ (dest blah)
                 (with-output-to-file dest
                   #:exists 'replace
                   (λ ()
                     (display
                      (pretty-format/write
                       `(module ,this-mod scheme/base
                          (require (prefix-in main: (planet synx/main:1))
                                   (prefix-in sub: ,that-mod))
                          (main:run))))
                     (newline)))))
              ; always make the exe
              (let ()
                (define racket (find-executable-path "racket"))
                (define raco (find-executable-path "raco"))
                (define needs-gui? (not (parameterize
                                            ((current-error-port (open-output-nowhere)))
                                          (system* racket "-l" "racket/base" "-t" (path->string filename)))))
                (apply system* raco "exe" "-o" (path->string exe)
                       (append
                        (list "--collects-path" (path->string (car (reverse (current-library-collection-paths)))))
                        (if needs-gui?
                            '("--gui")
                            '())
                        (list (path->string dest))))))))
   (void))

(main:register! generate)

(provide generate)