#!/bin/sh

# ybcon start script

EXENAME=ybcon

# Default location of the executable
defaultBinLocation=/opt/libexec/ybcon

usage() {
  if [ "$1" = false ]; then echo "Invalid arguments, usage:"; fi
  echo "$EXENAME [--version] [-h|--help] [-p|--printresult] file"
  if [ "$1" = true ]; then
    echo "        --version Print the version"
    echo "        -h or --help What you're seeing right now"
    echo "        -p or --printresult Enable printing the transpilation result to stdout"
  fi
}

usageExit() {
  usage false
  exit 0
}

args="";
run=false;
skipArgsIteration=false;

newArgs() {
  if [ "$args" = "" ]; then
    args="$args$1"
  else
    args="$args $1"
  fi
}

if [ "$#" != 0 ]; then
  if [ "$#" = 1 ]; then
    if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
      usage true
      exit 0;
    elif [ "$1" = "-p" ] || [ "$1" = "--printresult" ]; then
      usage false; exit 0;
    elif [ "$1" = "--version" ]; then
      run=true
      args="$1"
      skipArgsIteration=true;
    fi
  fi
  if [ "$skipArgsIteration" = false ]; then
    for it in "$@"
    do
      case "$it" in
        -h | --help | --version )
          usageExit ;;
        -p | --printresult )
          if test "${args#*$it}" = "$args"; then
            newArgs "$it"
          else
            usageExit
          fi ;;
        *.ybcon )
          newArgs "$it"
          run=true ;;
        * )
          usageExit ;;
      esac
    done
  fi
else
  usage false
fi

runIt() { eval "$1" " $args"; }

if [ "$run" = true ]; then
  if [ -f $defaultBinLocation ]; then
    runIt "$defaultBinLocation"
  elif [ -f ybcon ]; then
    runIt "./ybcon"
  fi
fi