#!/bin/bash

##### Convenience:
erro() { printf "%s\n" "$*" >&2; }

##### Set defaults:
SUPPRESS_ERR=YES
USE_NAILGUN=YES
LANGUAGE=Python

##### Extract command line options:
while [[ $1 = -* ]]
do
  case $1 in
    -h|--help)
      echo
      echo "Usage:"
      echo "  fosgen [-d] [-j] [-l LANGUAGE] FILE"
      echo
      echo "Writes to standard output the code generated from the fostr"
      echo "program in FILE, targeting the specified LANGUAGE (which"
      echo "defaults to Python)."
      echo
      echo "The -d option writes diagnostic output to standard error."
      echo "The -j option uses the Spoofax Sunshine JAR directly, rather"
      echo "than via nailgun."
      exit
      ;;
    -d)
      SUPPRESS_ERR=''
      ;;
    -j)
      USE_NAILGUN=''
      ;;
    -l)
      shift
      LANGUAGE="$1"
      ;;
  esac
  shift
done

##### Get positional arguments:
PROGRAM=$1

##### Corral resources:
BINDIR=$(dirname $BASH_SOURCE)
SUNJAR="$BINDIR/../lib/sunshine.jar"
PROJDIR="$BINDIR/.."

if [[ ! -f $SUNJAR ]]; then
  erro "Please download the Spoofax Sunshine jar to the lib directory."
  erro "Recommended command:"
  erro "  curl -o lib/sunshine.jar -L 'http://artifacts.metaborg.org/service/local/artifact/maven/redirect?r=snapshots&g=org.metaborg&a=org.metaborg.sunshine2&v=LATEST'"
  exit 1
fi

if [[ ! $MVN_REPO ]]; then
  MVN_REPO="$HOME/.m2/repository"
fi
if [[ ! -d $MVN_REPO ]]; then
  MVN_REPO="/root/.m2/repository"
fi
if [[ ! -d $MVN_REPO ]]; then
  erro "Cannot find your Maven repository. Please set environment variable"
  erro "MVN_REPO to its full path and re-run."
  exit 1
fi

##### Perform the code generation:
if [[ $SUPPRESS_ERR ]]
then
  exec 2>/dev/null
fi

if [[ $USE_NAILGUN ]]
then
  if [[ $SUPPRESS_ERR ]]
  then
    $BINDIR/let_sun_shine
  else
    $BINDIR/let_sun_shine noisy
  fi
  $BINDIR/ng sunshine transform -p $PROJDIR -n $LANGUAGE -i $PROGRAM
  exit $?
fi

java -jar $SUNJAR transform -p $PROJDIR -l $PROJDIR -l $MVN_REPO -n $LANGUAGE -i $PROGRAM
exit $?