#!/usr/bin/env bash

# This snippet is sourced by the launcher scripts generated by toolcommands.py.

brand="\e[0;1;34m[$_GF_APPNAME]\e[0m"

debrief()
{
    exitcode=$?

    # Report command exit code
    exitcolor=32  # green
    [ $exitcode -ne 0 ] && exitcolor=31  # red
    printf "\n%b %s \e[${exitcolor}m$exitcode\e[0m" "$brand" "$_GF_EXITMESSAGE"


    while true; do
      # Ask user whether to start a shell or exit
      printf "\n%b %s " "$brand" "$_GF_KEYPROMPT"

      IFS='' read -rn1 reply
      reply="$(echo "$reply" | tr '[:upper:]' '[:lower:]')"  # make lowercase
      [[ "$reply" == $'\033' || "$reply" == $_GF_NKEY ]] && exit  # ESC or 'n'
      [[ "$reply" == ''      || "$reply" == $_GF_YKEY ]] && break  # ENTER or 'y'
    done
    printf "\n\n"
}

# Enter workdir (some terminals ignore the cwd)
cd "$_GF_WORKDIR" || debrief

# Run user command (if we just clicked the Terminal button, this would be empty)
if [ -n "$_GF_COMMAND" ]; then
    printf "%b \e[4m%s\e[0m \e[2m(%s)\e[0m\n" "$brand" "$_GF_COMMAND" "$_GF_WORKDIR"
    eval "$_GF_COMMAND"
    debrief
fi

# Drop into a shell
exec ${SHELL:-/usr/bin/sh}
