#!/bin/bash

DIRNAME=$(readlink -f "$(dirname $0)/..")

# Build riskscape first
if [ -t 1 ]; then
    # if stdout is a terminal, run gradlew and write out the last line of output to stdout
    # (constantly updating)
    (cd $DIRNAME && set -o pipefail; ./gradlew installdist 2>&1 | while IFS= read -r line; do
        cols=$(tput cols 2>/dev/tty || echo 120)
        # truncate to a single line (using console width)
        line="${line:0:$((cols - 9))}"
        printf '\r%-*s' "$cols" "[gradle] $line" >/dev/tty
    done
    printf '\n' >/dev/tty) || exit $?
else
    # if stdout is a file, e.g. we are redirecting riskscape output, then each gradle output
    # to stderr instead (but with a prefix)
    (cd $DIRNAME && set -o pipefail; ./gradlew installdist 2>&1 | while IFS= read -r line; do
        echo "[gradle] $line" >&2
    done) || exit $?
fi

exec $DIRNAME/engine/app/build/install/riskscape/bin/riskscape "$@"
