#! /bin/bash
#
# Copyright (c) 2009 Stephen C. Gilardi, Meikel Brandmeyer.
# All rights reserved.
#
# The use and distribution terms for this software are covered by the Eclipse
# Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
# be found in the file epl-v10.html at the root of this distribution.  By using
# this software in any fashion, you are agreeing to be bound by the terms of
# this license.  You must not remove this notice, or any other, from this
# software.
#
# cljc Compiles the given namespaces to the destination directory creating
#      it if necessary. The namespaces are looked for in the given source
#      directory.
#
# Meikel Brandmeyer <mb <at> kokta.de>
# Created 14 February 2009
#
# Based on Stephen C. Gilardis bash launcher.
#
# Environment variables:
#
#  CLOJURE_EXT  The path to a directory containing (either directly or as
#               symbolic links) jar files and/or directories whose paths
#               should be in Clojure's classpath. The value of the
#               CLASSPATH environment variable for Clojure will be a list
#               of these paths followed by the previous value of CLASSPATH
#               (if any).
#
#  CLOJURE_JAVA The command to launch a JVM instance for Clojure
#               default: java
#               example: /usr/local/bin/java6
#
#  CLOJURE_OPTS Java options for this JVM instance
#               default:
#               example:"-Xms32M -Xmx128M -server"

usage() {
    echo "Usage: $0 [-s <srcdir>] [-d <destdir>] [--] name.space [...]"
    exit 1
}

srcdir="src"
classesdir="classes"

namespaces_start_at=0

while getopts h-s:d: flag; do
    case $flag in
        h)
        usage;;

        s)
        srcdir="$OPTARG";;

        d)
        classesdir="$OPTARG";;

        ?)
        usage;;
    esac
done

shift $((OPTIND - 1))

if [ \! -d "${classesdir}" ]; then
    mkdir -p "${classesdir}"
    if [ $? -ne 0 ]; then
        echo "ERROR: ${classesdir} could not be created!"
        exit 1
    fi
fi

if [ -d "${CLOJURE_EXT}" ]; then
    EXT="$(find ${CLOJURE_EXT} -mindepth 1 -maxdepth 1 -print0 | tr \\0 \:)"
    CLASSPATH="${EXT%:}${CLASSPATH:+:${CLASSPATH}}"
fi

CLASSPATH="${srcdir}:${classesdir}${CLASSPATH:+:${CLASSPATH}}"

export CLASSPATH

JAVA="${CLOJURE_JAVA:-java}"
OPTS="${CLOJURE_OPTS:-}"
MAIN="${CLOJURE_MAIN:-clojure.lang.Compile}"

exec $JAVA $OPTS "-Dclojure.compile.path=${classesdir}" $MAIN "$@"
