#!/usr/bin/env bash

# build.sh sets these env vars as output:
# DEXORDER_WEB_VERSION
# DEXORDER_WEB_IMAGE

DOCKER=docker
CONTAINER=dexorder-web

SCRIPT_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
WEB_HOME=${WEB_HOME:-$SCRIPT_HOME}

cd $WEB_HOME || exit 1

DIRTY="$( git status | grep "Changes " )"
if [ "$DIRTY" != "" ] && [ "$1" != "dev" ]; then
    echo "$WEB_HOME has uncommited changes"
    exit 1
fi

DEXORDER_WEB_VERSION="$( git log --oneline | head -1 | cut -d ' ' -f 1 )"
if [ "$1" == "dev" ]; then
  shift
  DEXORDER_WEB_VERSION="dev`date +%Y%m%d%H%M%S`"
fi
DEXORDER_WEB_IMAGE="gcr.io/cointrader-211623/$CONTAINER:$DEXORDER_WEB_VERSION"
echo $DEXORDER_WEB_IMAGE

echo "const dexorderWebVersion='$DEXORDER_WEB_VERSION'" > "$WEB_HOME/public/version.js"
npm run build

DOCKERFILE=deploy/Dockerfile
$DOCKER build -f "$DOCKERFILE" -t "$DEXORDER_WEB_IMAGE" .
if [ $? != 0 ]; then
    echo 'container build failed'
    exit 1
fi

export DEXORDER_WEB_VERSION
export DEXORDER_WEB_IMAGE

echo $(date) build complete
