#!/bin/sh

SkipCheckRepo=false

if [ -z "$SkipCheckRepo" ] && [ -n "$(git status --porcelain)" ]; then
    echo "Repo is dirty. Aborting..."
    exit 1
fi

BUILT_TIME=$(date +'%B-%d,-%Y-@-%T')
BUILD_HASH=$(git rev-parse HEAD)
if [ "$CI_COMMIT_BRANCH" ]; then
    HOSTNAME="GitLab"
    BUILD_BRANCH=$CI_COMMIT_BRANCH
else
    HOSTNAME=$(hostname -f)
    BUILD_BRANCH=$(git rev-parse --abbrev-ref HEAD)
fi

# This allow to set the default path, if script used outside makefile
if [ -z "$OUT_PATH" ]; then
    OUT_PATH="./build/out/distribution"
fi

mkdir -p "$OUT_PATH"

go generate ./...

# Generate the native version
env CGO_ENABLED=0 go build -mod vendor -o ${OUT_PATH}/qfixdpl -ldflags "-X quantex.com/qfixdpl/src/app/version.hostname=${HOSTNAME} -X quantex.com/qfixdpl/src/app/version.builtTime=${BUILT_TIME} -X quantex.com/qfixdpl/src/app/version.buildHash=${BUILD_HASH} -X quantex.com/qfixdpl/src/app/version.buildBranch=${BUILD_BRANCH}"  *.go

gzip -kf "${OUT_PATH}"/qfixdpl

# if no environment argument, set to default value dev
if [ -z "$1" ]; then
    ENV="dev"
else
    ENV="$1"
fi

if COMMIT_MSG=$(QUANTEX_ENVIRONMENT=$ENV "${OUT_PATH}/qfixdpl" -v 2>/dev/null); then
    echo "$COMMIT_MSG"
else
    echo "---------------------------------"
    echo "QFIXDPL"
    echo "Built at: ${BUILT_TIME}"
    echo "Branch: ${BUILD_BRANCH}"
    echo "SHA: ${BUILD_HASH}"
    echo "Built from ${HOSTNAME}"
    echo "Powered by Quantex Technologies"
    echo "---------------------------------"
fi

