#!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#

(unless (find-package :uiop)
  (ql:quickload :uiop :silent t))

(ql:quickload :prove :silent t)

(when (uiop:getenv "COVERALLS")
  (ql:quickload '(:cl-coveralls :split-sequence) :silent t))

(defun print-error (format-string &rest format-args)
  (format *error-output* "~&[Error] ")
  (apply #'format *error-output*
         format-string format-args)
  (fresh-line *error-output*)
  (uiop:quit -1))

(defun main (&rest test-files)
  (let (reporter color)
    (when (or (string= (first test-files) "-r")
              (string= (first test-files) "--reporter"))
      (setf reporter (second test-files)
            test-files (cddr test-files)))
    (flet ((not-color-p (arg) (or (string= "-c" arg)
                                  (string= "--without-colors" arg))))
      (setf color (not (loop :for a :in test-files :thereis (not-color-p a)))
            test-files (remove-if #'not-color-p test-files)))
    (labels ((run-tests ()
               (not
                (some #'null
                      (mapcar (lambda (test-file)
                                (unless (probe-file test-file)
                                  (print-error "test file '~A' does not exist." test-file))
                                (let ((prove.output:*default-reporter*
                                        (or reporter
                                            prove.output:*default-reporter*)))
                                  (unless (string= (pathname-type (probe-file test-file)) "asd")
                                    (print-error "test file '~A' is not an asd file." test-file))
                                  (let ((test-file (probe-file test-file))
                                        (prove:*enable-colors* color))
                                    (#+asdf3.3 asdf::with-asdf-session
                                     #-asdf3.3 asdf::with-asdf-cache ()
                                      (asdf::load-asd test-file)
                                      (prove:run-test-system (asdf:find-system (pathname-name test-file)))))))
                              test-files)))))
      (or #.(if (uiop:getenv "COVERALLS")
                `(,(intern (string :with-coveralls) :coveralls)
                  (:exclude
                   (,(intern (string :split-sequence) :split-sequence)
                    #\: (or (uiop:getenv "COVERAGE_EXCLUDE") "")
                    :remove-empty-subseqs t))
                  (run-tests))
                '(run-tests))
          (uiop:quit -1)))))
