#!/usr/bin/env bash

# This script must be run within the ClojureScript top-level project
# directory.

set -e

if [[ -z "$CLJS_SCRIPT_QUIET" ]]; then
  set -x
fi

cd `dirname $0`/..
rm -rf target
rm -f resources/brepl_client.js

POM_TEMPLATE="pom.template.xml"
POM_FILE="pom.xml"
CLJS_SCRIPT_MVN_OPTS=${CLJS_SCRIPT_MVN_OPTS:-""}

export MAVEN_OPTS="${MAVEN_OPTS} --add-opens java.base/java.util=ALL-UNNAMED"

# The command `git describe --match v0.0` will return a string like
#
# v0.0-856-g329708b
#
# where 856 is the number of commits since the v0.0 tag. It will always
# find the v0.0 tag and will always return the total number of commits (even
# if the tag is v0.0.1).
MAJOR="1"
MINOR="12"
REVISION=`git --no-replace-objects describe --match v$MAJOR.$MINOR`

# Extract the version number from the string.
REVISION_REGEX="v[0-9]*\.[0-9]*-([0-9]*)-.*"
if [[ $REVISION =~ $REVISION_REGEX ]]
then
  REVISION="${BASH_REMATCH[1]}"
fi

TAG=r$MAJOR.$MINOR.$REVISION

sed -e s/CLOJURESCRIPT_VERSION/$MAJOR.$MINOR.$REVISION/ < "$POM_TEMPLATE" > "$POM_FILE"

COMP_FILE=`mktemp /tmp/compiler.clj.XXXXXXXXXXX`
sed -e 's/^.def ^:dynamic \*clojurescript-version\*.*$/(def ^:dynamic *clojurescript-version* {:major '"$MAJOR"', :minor '"$MINOR"', :qualifier '"$REVISION"'})/' src/main/clojure/cljs/util.cljc > $COMP_FILE
mv $COMP_FILE src/main/clojure/cljs/util.cljc

CLJS_FILE=`mktemp /tmp/core.cljs.XXXXXXXXXXX`
sed -e 's/^.def \*clojurescript-version\*.*$/(def *clojurescript-version* '\""$MAJOR.$MINOR.$REVISION"\"')/' src/main/cljs/cljs/core.cljs > $CLJS_FILE
mv $CLJS_FILE src/main/cljs/cljs/core.cljs

rm -f src/main/cljs/cljs/core.aot.js
rm -f src/main/cljs/cljs/core.aot.js.map
rm -f src/main/cljs/cljs/core.cljs.cache.aot.edn
rm -f src/main/cljs/cljs/core.cljs.cache.aot.json

./script/aot_core

AOT_FILE=`mktemp /tmp/core.aot.js.XXXXXXXXXXX`
sed -e 's/0.0.0000/$MAJOR.$MINOR.$REVISION/' src/main/cljs/cljs/core.aot.js > $AOT_FILE
mv $AOT_FILE src/main/cljs/cljs/core.aot.js

AOT_CACHE_FILE=`mktemp /tmp/core.cljs.cache.aot.edn.XXXXXXXXXXX`
sed -e 's/0.0.0000/$MAJOR.$MINOR.$REVISION/' src/main/cljs/cljs/core.cljs.cache.aot.edn > $AOT_CACHE_FILE
mv $AOT_CACHE_FILE src/main/cljs/cljs/core.cljs.cache.aot.edn

# For Hudson server
if [ "$HUDSON" = "true" ]; then
    mvn -B -ntp --fail-at-end -DskipStaging=true -Psign $CLJS_SCRIPT_MVN_OPTS clean deploy

    echo "Creating tag $TAG"
    git tag -f "$TAG"
    git push origin "$TAG"
else
    echo "Skipping remote deployment and Git tag because we are not on Hudson."
    mvn -B -ntp $CLJS_SCRIPT_MVN_OPTS clean install
fi

rm -f src/main/cljs/cljs/core.aot.js
rm -f src/main/cljs/cljs/core.aot.js.map
rm -f src/main/cljs/cljs/core.cljs.cache.aot.edn
rm -f src/main/cljs/cljs/core.cljs.cache.aot.json
