#!/bin/sh

# ybcon start script

EXENAME=ybcon

scriptDir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)

# Location of the executable
defaultBinLocation="$scriptDir/../libexec/ybcon"

usage() {
  if [ "$1" = false ]; then echo "Invalid arguments, usage:"; fi
  echo "$EXENAME [--version] [--buildInfo] [-h|--help] [--parallel] [--target=<target>] [--newlines=on/off] [-p|--printresult] [-t|--text] <file>"
  if [ "$1" = true ]; then
    echo "        --version Print the version"
    echo "        --buildInfo Print informations about how the ybcon executable was built"
    echo "        -h or --help What you're seeing right now"
    echo "        --parallel Transpile files in parallel mode"
    echo "        --target=<target> Set the transpilation target"
    echo "        --newlines=on/off Enable or disable new lines"
    echo "        -p or --printresult Enable printing the transpilation result to stdout"
    echo "        -t or --text Transpile text provided after this argument (implies -p)"
    echo "        -o or --output Output the transpiled file(s) to the specified directory"
    printf "\n"
  fi
}

usageExit() {
  usage false
  exit 0
}; helpExit() { usage true; exit 0; }

arguments="";
run=false;

if [ "$#" != 0 ]; then
  if [ "$#" = 1 ]; then
    case "$1" in
      -h | --help )
        helpExit ;;
      --version | --buildInfo | *.ybcon )
        run=true ;;
      * )
        usageExit ;;
    esac
  else
    text_provided=false
    for it in "$@"
      do
        case "$it" in
          -p | --printresult | --parallel | --target=* | --newlines=on | --newlines=off )
            if [ "${arguments#*$it}" != "$arguments" ] && [ "${arguments%*-$it}" = "${arguments#*-$it}" ]; then
              usageExit
            fi ;;
          -t | --text )
            text_provided=true ;;
          * )
            if [ $text_provided = true ] || [ "${it%*.ybcon}" != "$it" ]; then
              run=true
            else
              usageExit
            fi ;;
        esac
        if [ "$arguments" != "" ]; then
          arguments="$arguments "
        fi
        arguments="$arguments$it"
      done
    if test $run = false ; then usageExit; fi
  fi
else
  usage false
fi

if [ "$run" = true ]; then
  if [ -f "$defaultBinLocation" ]; then
    exec "$defaultBinLocation" "$@"
  else
    echo "Yerbacon executable not found at $defaultBinLocation"
  fi
fi