#! /bin/sh

set -e

dir=`dirname "$0"`

pb_dir="$dir/ChezScheme/boot/pb"

use_cs=maybe
use_bc=maybe
supplied_racket=no
enable_boothelp=

# We don't have to detect conflicts like `--enable-csdefault --enable-bcdefault`,
# since the `configure` scripts will do that, but  we have to figure out which
# configure scripts to run

for arg in $*; do 
    case "$arg" in
        --enable-cs | --enable-csdefault)
            use_cs=yes
            ;;
        --enable-bc | --enable-bcdefault | --enable-cgcdefault)
            use_bc=yes
            ;;
        --enable-csonly)
            use_cs=yes
            use_bc=no
            ;;
        --enable-bconly)
            use_cs=no
            use_bc=yes
            ;;
        --enable-racket=*)
            supplied_racket=yes
            ;;
        --help | -h)
            echo $0:
            echo see --help-bc or --help-cs, since the Racket CS build and the
            echo Racket BC build support different options. If you use options
            echo that build both CS and BC, then you can mix options that apply
            echo to both or either kind of build.
            exit 0
            ;;
        --help-bc)
            exec "$dir/bc/configure" --help
            ;;
        --help-cs)
            exec "$dir/cs/c/configure" --help
            ;;
    esac
done

# Select default build if none specified:
if test "$use_bc" = maybe ; then
    if test "$use_cs" = maybe ; then
        use_bc=yes
        use_cs=no
    elif test "$use_cs" = no ; then
        use_bc=yes
    elif test -d "$pb_dir" -o $supplied_racket = yes ; then
        use_bc=no
    else
        echo No "$pb_dir", so enabling BC build
        use_bc=yes
        enable_boothelp=--enable-boothelp
    fi
elif test "$use_cs" = "maybe" ; then
    use_cs=no
fi

if test "$use_cs" = "yes" ; then
    if test $use_bc = no  -a $supplied_racket = no -a ! -d "$pb_dir" ; then
        echo $0: must have $pb_dir or --enable-racket=... for --enable-csonly
        exit 1
    fi

    echo "=== Racket CS enabled"

    mkdir -p cs/c
    case "$dir" in
        /*)
            (cd cs/c && "$dir/cs/c/configure" ${1+"$@"})
            ;;
        *)
            (cd cs/c && "../../$dir/cs/c/configure" ${1+"$@"})
            ;;
    esac
fi

if test "$use_bc" = "yes" ; then
    echo "=== Racket BC enabled"

    mkdir -p bc
    case "$dir" in
        /*)
            (cd bc && "$dir/bc/configure" ${1+"$@"})
            ;;
        *)
            (cd bc && "../$dir/bc/configure" ${1+"$@"})
            ;;
    esac
fi

if test "$use_bc" = "no" ; then
    exec "$dir/cfg-cs" $enable_boothelp ${1+"$@"}
else
    exec "$dir/cfg-bc" $enable_boothelp ${1+"$@"}
fi
