loader.ss
#lang scheme/base
(require mzlib/trace
         scheme/contract
         scheme/port
         scheme/system
         scheme/string
         mzlib/etc
         )

;; (define (escape-path

(define (escape-path path)
  (case (system-type 'os)
    ((windows) 
     (if (regexp-match #px"\\s" path)
         (string-append "\"" path "\"")
         path))
    (else
     (if (regexp-match #px"\\s" path)
         (regexp-replace* #px"(\\s)" path "\\\\1")
         path))))

(define (yui-compress! path min-path)
  (let ((cerr (open-output-bytes)))
    (parameterize ((current-error-port cerr))
      (let ((res (system (string-join 
                          (list "java" 
                                "-jar" 
                                ;; escaping path... ensure there are no spaces...
                                (escape-path (path->string 
                                              (build-path (this-expression-source-directory)
                                                          "yuicompressor.jar")))
                                "-o" 
                                (escape-path (path->string min-path)) 
                                (escape-path (path->string path)))
                          " "))))
        (unless res ;; failed...
          (error 'compress! (get-output-string cerr)))))))

(trace yui-compress!)

(define (open-js/css-files paths (compress! yui-compress!))
  (define (min-path-helper path)
    (string->path (string-append (path->string path) ".min")))
  (define (helper path)
    (if (not compress!)
        (open-input-file path)
        (let ((min-path (min-path-helper path)))
          (when (or (not (file-exists? min-path))
                    (> (file-or-directory-modify-seconds path)
                       (file-or-directory-modify-seconds min-path)))
            (compress! path min-path))
          (open-input-file min-path))))
  (apply input-port-append #t (map helper paths)))

(define (open-js/css-files/base paths base (compress! yui-compress!))
  (define (helper path)
    (apply build-path base (regexp-split #px"/" 
                                         (if (path? path) (path->string path)
                                             path))))
  (open-js/css-files (map helper paths) compress!))

(provide/contract 
 (yui-compress! (-> path-string? path-string? any))
 (open-js/css-files (->* ((listof path-string?))
                             ((-> path-string? path-string? any)) 
                             input-port?))
 (open-js/css-files/base (->* ((listof path-string?) path-string?)
                                  ((or/c #f (-> path-string? path-string? any)))
                                  input-port?))
 )