#!/bin/bash
set -e

HERE=$(dirname "$(readlink --canonicalize "$BASH_SOURCE")")
. "$HERE/_env"
. "$HERE/_build"

DEBUG=${DEBUG:-false}
FAST_COMPILER=${FAST_COMPILER:-false}
FAST_LINKER=${FAST_LINKER:-false}
NIGHTLY=${NIGHTLY:-false}

export RUSTFLAGS=
CARGO_CHANNEL=
CARGO_ARGS=
LINKER=

function help () {
    echo -e "Usage: $BLUE$(basename "$0")$RESET [${BLUE}-d$RESET] [${BLUE}-c$RESET] [${BLUE}-l$RESET] [${BLUE}-n$RESET] [${BLUE}-h$RESET]"
    echo ''
    echo -e "  ${BLUE}-d$RESET = debug"
    echo -e "  ${BLUE}-c$RESET = fast compiler"
    echo -e "  ${BLUE}-l$RESET = fast linker"
    echo -e "  ${BLUE}-n$RESET = nightly Rust"
    echo -e "  ${BLUE}-h$RESET = this help"
    exit 1
}

while getopts :dclnh OPTION; do
    case "$OPTION" in
        d) DEBUG=true ;;
        c) FAST_COMPILER=true ;;
        l) FAST_LINKER=true ;;
        n) NIGHTLY=true ;;
        h) help ;;
        ?) echo -e "Unsupported flag: ${RED}-$OPTARG$RESET" ; echo '' ; help ;;
    esac
done

m 'running examples...' "$CYAN"

handle_debug_build
handle_fast_compiler
handle_fast_linker
handle_nightly

cd "$ROOT"

for EXAMPLE in $(cargo_examples); do
    m "\nexample: $EXAMPLE\n" "$RED"
	cargo $CARGO_CHANNEL run --quiet --example "$EXAMPLE"  --features=anyhow,serde,backtrace-external $CARGO_ARGS
done
