#!/usr/bin/env bash

# Set failures
set -e
set -o pipefail

# Builds a stand-alone directory with all the files and dependencies for this theme.
# Should be called via the project Makefile (`make build`) to ensure dependencies are met.

BUILD_DIR_BASE="$1"
HASH="$2"

onfail() {
    # If the previous command failed, print an error message to standard
    # error and bail out.
    if [ $? -ne 0 ]; then
        echo "$@" 1>&2
        exit 1
    fi
}

echo "Building commit $HASH of project $PROJECT_NAME in $BUILD_DIR_BASE."
BUILD_DIR="$BUILD_DIR_BASE/$HASH"
rm -rf $BUILD_DIR
mkdir -p $BUILD_DIR
echo $HASH > $BUILD_DIR/git_hash
onfail "ERROR: failed to put git hash into build directory."

echo "Installing NPM packages"
make npm
onfail "ERROR: failed to install npm packages"

echo "Test for linting issues"
make lint
onfail "ERROR: found linting errors"

echo "Running gulp"
make gulp-build
onfail "ERROR: failed to run gulp script."

cp -r build $BUILD_DIR
onfail "ERROR: failed to copy to build directory."

exit 0
