#!/usr/bin/env -S guile --no-auto-compile -s

This is a headless, minimal version of Studio.

It evaluates a given script (in the same sandboxed environment),
finds every shape, and saves them to an STL file.

TODO: Error handling is non-existent.
!#

(use-modules (libfive kernel) (libfive sandbox) (libfive vec))
(use-modules (ice-9 textual-ports))

(define args (program-arguments))

(when (not (eq? (length args) 3))
  (format #t "Usage: ~A input.io output.stl\n  Headless utility to export meshes from a Studio file\n" (car args))
  (exit 1))

(define text (get-string-all (open-input-file (cadr args))))
(define r (eval-sandboxed text))

(define shapes
  (let f ((r r))
    (cond ((eq? 0 (length r)) '())
          ((eq? (caar r) 'error) (error (car r)))
          ((shape? (cadar r)) (append (cons (cadar r) (f (cdr r)))))
          (else (f (cdr r))))))


(define filename (caddr args))

;; Extract bounds from the six-element list
(define upper (apply vec3 (cdddr global-bounds)))
(list-cdr-set! global-bounds 2 '())
(define lower (apply vec3 global-bounds))

(shapes->mesh shapes filename lower upper global-resolution global-quality)
