#!/bin/sh
set -e

if [ "$#" -eq 2 -a \( \( "$1" = "--keep" \) -o \( "$1" = "-k" \) \) ]; then
  INPUT="$2"
  BASE=$(dirname "$INPUT")/$(basename "$INPUT" .subv)
elif [ "$#" -eq 1 ]; then
  INPUT="$1"
  DIR=$(mktemp -dt subv.XXXXXX)
  BASE="$DIR"/$(basename "$INPUT" .subv)
else
  echo "Error: invalid arguments" 1>&2
  echo "Usage: $0 [-k|--keep] input.subv" 1>&2
  exit 1
fi

msg() {
  echo -e "\e[1;32m$1\e[00m" 1>&2
}

msg "OUTPUTTING TO $BASE.*"

msg VALIDATING...
./validate.py <"$INPUT"   >"$BASE.valid"
msg SURVEYING...
./survey.py   <"$BASE.valid"  >"$BASE.survey"
msg FORMATTING...
./format.py   <"$BASE.survey" >"$BASE.format"
msg PACKING...
./pack.py     <"$BASE.format" >"$BASE.pack"
msg ELFING...
./elf.py      <"$BASE.pack"   >"$BASE.elf"
msg DONE!

if [ -n "$DIR" ]; then
  cat "$BASE.elf"
  rm "$BASE".*
  rmdir "$DIR"
fi
