#! /usr/bin/csi -script
;;;; extend-chicken - Recompile compiler with added library units - felix


(define modules '("support.c" "batch-driver.c" "c-backend.c" "compiler.c" "c-platform.c" "chicken.scm"))

(define makefile #<<EOF
CC = gcc
CFLAGS = `chicken-config -cflags` -DC_DEFAULT_TARGET_STACK_SIZE=12228
SFLAGS = -optimize-level 2 -quiet -heap-size 16m
HOMEDIR = 
SC = chicken
.SUFFIXES : .scm
~A : chicken.o support.o compiler.o c-platform.o c-backend.o batch-driver.o ~A
	$(CC) $(CFLAGS) $< `chicken-config -libs -extra-libs` -o $@
chicken.o : chicken.scm
	$(SC) $< $(SFLAGS) -postlude "(declare ~A)" -output-file chicken.c
	$(CC) $(CFLAGS) chicken.c -c -o $@

EOF
)

(define (usage)
  (display #<<EOF
Usage: extend-chicken UNITNAME | OPTION ...

  -output-file FILENAME  generate compiler with this name (defaults to 'chicken-2')
  -do-not-build          generate makefile.FILENAME, but do not invoke `make'

EOF
) 
  (exit 64) )

(define (invoke fstr . args)
  (let ([str (apply sprintf fstr args)])
    (print str)
    (unless (zero? (system str)) (error "shell command failed")) ) )

(let ([out "chicken-2"]
      [dontbuild #f]
      [units '()] )
  (let loop ([args (command-line-arguments)])
    (cond [(null? args)
	   (when (null? units) (usage))
	   (for-each
	    (lambda (f)
	      (unless (file-exists? f)
		(invoke "cp /src/~A ." f) ) )
	    modules)
	   (let ([oname (sprintf "makefile.~A" out)]
		 [us (reverse (map string->symbol units))])	  
	     (with-output-to-file (sprintf "makefile.~A" out)
	       (lambda () (printf makefile out (string-concatenate units " ") (cons 'uses us)) ) )
	     (unless dontbuild
	       (invoke (sprintf "make -f ~A" oname))
	       (invoke (sprintf "rm -f ~A" oname)) ) ) ]
	  [(string=? "-output-file" (car args))
	   (unless (pair? (cdr args)) (usage))
	   (set! out (cadr args))
	   (loop (cddr args)) ]
	  [(string=? "-do-not-build" (car args))
	   (set! dontbuild #t)
	   (loop (cdr args)) ]
	  [else
	   (set! units (cons (car args) units))
	   (loop (cdr args)) ] ) ) )
