#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

if ! which go > /dev/null; then
  echo "golang needs to be installed"
  exit 1
fi

if [ -z "$TARBALL_URL" ]
then
  echo "\$TARBALL_URL env not set"
  exit 1
fi

if [ -z "$OUTPUT_DIR" ]
then
  echo "\$OUTPUT_DIR env not set"
  exit 1
fi

if [ -z "$BUILD_MODE" ]
then
  echo "\$BUILD_MODE env not set"
	exit 1
fi

if [ "$BUILD_MODE" != "binary" ] && [ "$BUILD_MODE" != "sources" ] && [ "$BUILD_MODE" != "vendor" ]
then
  echo "\$BUILD_MODE env must be one of: 'binary', 'sources', 'vendor'"
	exit 1
fi

# Make sure we get the first element in the GOPATH environment variable.
# Some systems have multiple values set
GOPATH_DIR=$(echo -n ${GOPATH} | cut -d: -f1 | tr -d '\n')
PROJECT_NAME="apicast-operator"
BINARY_NAME=${PROJECT_NAME}
REPO_PATH="github.com/3scale"
BUILD_PATH="${REPO_PATH}/${PROJECT_NAME}/cmd/manager"
# Get the name of the file only from the URL string.
# We do this by pattern matching the longest matching pattern
# of "*/". This is, until the latest / and we remove that matched
# pattern
SOURCES_TARBALL=/tmp/${TARBALL_URL##*/}

# Download sources
curl -L ${TARBALL_URL} -o ${SOURCES_TARBALL}
if [ $BUILD_MODE == "sources" ]
then
  mv ${SOURCES_TARBALL} ${OUTPUT_DIR}/${PROJECT_NAME}-${TARBALL_URL##*/}
  exit 0
fi

# Extract sources
mkdir -p ${GOPATH_DIR}/src/${REPO_PATH}
tar -xzf ${SOURCES_TARBALL} -C ${GOPATH_DIR}/src/${REPO_PATH}
# Rename apicast-operator-* directory to apicast-operator
mv ${GOPATH_DIR}/src/${REPO_PATH}/${PROJECT_NAME}{-*,}

# Download dependencies
pushd ${GOPATH_DIR}/src/${REPO_PATH}/${PROJECT_NAME} > /dev/null
echo "Downloading dependencies..."
GO111MODULE=on go mod vendor

if [ $BUILD_MODE == "binary" ]
then
  # Build operator
  echo "building "${BINARY_NAME}"..."
  GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${OUTPUT_DIR}/${BINARY_NAME} ${BUILD_PATH}
  # package binary
  tar -C ${OUTPUT_DIR} -zcf ${OUTPUT_DIR}/binary-${BINARY_NAME}.tar.gz ${BINARY_NAME}
  rm -f ${OUTPUT_DIR}/${BINARY_NAME}
fi

if [ $BUILD_MODE == "vendor" ]
then
  # package vendor
  tar -czf ${OUTPUT_DIR}/vendor-${PROJECT_NAME}.tar.gz vendor
  rm -rf ${OUTPUT_DIR}/vendor
fi
