#!/usr/bin/fdscript --noherald
;; -*- Mode: fdscript -*-

(define (convert-args arglist)
  (let ((option-stream (open-string-stream))
	(filename-stream (open-string-stream)))
    (dolist (arg arglist)
      (cond ((eqv? (elt arg 0) #\-)
	     (display elt option-stream)
	     (display " " option-stream))
	    (else (display elt filename-stream)
		  (display " " filename-stream))))
    (cons (string-stream-contents option-stream)
	  (string-stream-contents filename-stream))))

(define (compile-command)
  (let ((output-file arg2)
	(compile-args (convert-args (cdr (cdr args)))))
    (system "ld -shared -o " output-file " -L/usr/lib "
	    (car compile-args) " " (cdr compile-args)
	    "-ldtypes -lframerd -lfdscript -lfdtext")))

(define (install-command)
  (let* ((install-file arg2)
	 (dest (stringout framerd_lib "/modules/" install-file))
	 (group (if (and (getenv "FRAMERD_GROUP")
			 (get-gid (getenv "FRAMERD_GROUP")))
		    (getenv "FRAMERD_GROUP")
		    (and (get-gid "framerd") "framerd"))))
    (if (has-suffix arg2 ".fdx") (copy-text-file arg2 dest)
	(copy-binary-file arg2 dest))
    (when group
      (system "chgrp " group " " dest)
      (system "chmod g+rw " dest))))

(define (main)
  (cond ((or (equal? arg1 "-c") (equal? arg1 "compile"))
	 (compile-command))
	((or (equal? arg1 "-i") (equal? arg1 "install"))
	 (install-command))
	((equal? arg1 "cflags")
	 (lineout "-fPIC -rdynamic -g -O2 -I/usr/include"))
	((equal? arg1 "libs")
	 (lineout " -L/usr/lib -ldtypes -lframerd -lfdscript -lfdtext"))
	((equal? arg1 "modules")
	 (lineout "/usr/share/framerd/modules"))))

