#!/bin/bash

# exit if any statement returns a non-zero exit code
set -e

# If the help is requested, then print that without running any of the prep commands
if [[ $* == *-h* ]];
then
    java -Xmx128m -cp $BIOR_LITE_HOME/conf:$BIOR_LITE_HOME/lib/* edu.mayo.cli.CommandLineApp edu.mayo.bior.cli.cmd.CreateCatalogCommand $0 $@
    exit;
fi

#check to make sure dependancies are installed and on the path
command -v tabix >/dev/null 2>&1 || { echo >&2 "I require tabix but it's not installed/on your path.  Aborting."; exit 1; }
command -v bgzip >/dev/null 2>&1 || { echo >&2 "I require bgzip but it's not installed/on your path.  Aborting."; exit 1; }
command -v grep >/dev/null 2>&1 || { echo >&2 "I require grep but it's not installed/on your path.  Aborting."; exit 1; }


# check java version
REQUIRED_MINOR_VERSION=6

# grab full version string from running "java -version"
VERSION=`java -Xmx64m -version 2>&1 | grep "java version" | awk '{ print substr($3, 2, length($3)-2); }'`

# parse out the minor version number
MINOR_VERSION=`echo $VERSION | cut -d . -f 2`

# check minor version, anything less than the required version is invalid
if [ $MINOR_VERSION -lt $REQUIRED_MINOR_VERSION ]; then
	echo "Invalid Java version $VERSION.  Java 1.$REQUIRED_MINOR_VERSION or higher is required."
	echo "You can check your java version by running: java -version"
	exit 1
fi

echo "Formatting Catalog... (Step 1/4)"
java -Xmx128m -cp $BIOR_LITE_HOME/conf:$BIOR_LITE_HOME/lib/* edu.mayo.cli.CommandLineApp edu.mayo.bior.cli.cmd.CreateCatalogCommand $0 $@

# OUTPUT will be filled in by the arguments provided on the command line, so start it blank
OUTPUT=""
isSorted="true"
function getParams() {
  while [ "$1" != "" ] ; do
    case $1 in
      --output )
        OUTPUT="$2"
        shift 2
        ;;
      -o )
        OUTPUT="$2"
        shift 2
        ;;
      --nosort )
        isSorted="false"
        shift 1
        ;;
      -n )
        isSorted="false"
        shift 1
        ;;
      * )
        shift
        ;;
    esac
  done
}

getParams  $*


echo "Sorting Catalog... (Step 2/4)"
if [ "$isSorted" == "true" ] ; then
  _bior_sort_catalog  ${OUTPUT} > "$OUTPUT.sorted"
  rm "${OUTPUT}"
else
  echo "  (User chose to NOT sort the catalog)"
  mv "$OUTPUT" "$OUTPUT.sorted"
fi

echo "Compressing Catalog...[${OUTPUT}] (Step 3/4)"
cat "$OUTPUT.sorted" | grep -v "^#" | bgzip > ${OUTPUT}.tsv.bgz ;
rm "${OUTPUT}.sorted"

echo "Indexing Catalog...(Step 4/4)"
tabix -s 1 -b 2 -e 3 ${OUTPUT}.tsv.bgz

echo "Done!"

