#!/bin/bash

# check for git
if command -v git &> /dev/null; then
    git="true"
fi

# check for Node
if command -v node &> /dev/null; then
    node="true"
fi

# check for node_modules
if [[ "$git" && "$node" ]]; then
    # if the node_modules directory doesn't exist
    if [[ -d node_modules ]]; then
        npm="true"
    fi
fi

# displays help text
function displayHelp() {
	cat <<HelpText
Usage: compile.sh [GULP FLAGS]

Falls back to ./compile-legacy.sh if Gulp's dependencies are missing.

HelpText

if [[ $"npm" ]]; then
    npx gulp
else
    cat <<HelpText
Gulp's dependencies are not installed.
HelpText
fi
}

flags="all"

if [[ "$1" == "" ]]; then
	#tip if no option
	echo "For more options see compile.sh -h."
else
	#parse options
	while [[ "$1" ]]; do
		case $1 in
			-h | --help)
				displayHelp
				exit 0
				;;
			*)
                flags="${flags} $1"
		esac
		shift
	done
fi

echo ""
if [[ ! "$git" ]]; then
    echo "git is not available, install it to use Gulp compiler."
fi

if [[ ! "$node" ]]; then
    echo "Node is not available, install it to use the Gulp compiler."
fi

if [[ ! "$npm" ]]; then
    echo "Node modules aren't installed, run 'npm install' to install them."
fi

if [[ ! "$git" || ! "$node" || ! "$npm" ]]; then
    echo ""
    echo "Gulp compiler dependencies not met, falling back to legacy compiler."
    echo "The legacy compiler is missing source map generation, but requires no other dependencies."
    echo "If you wish to always use the legacy compiler, run './compile-legacy.sh' instead."
    echo ""
    ./compile-legacy.sh $flags
    exit 0
fi

echo "Compiling using Gulp with these arguments: $flags"
echo ""
npx gulp $flags