#!/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 "$OPERATOR_BUILD_TARBALL" ]
then
  echo "\$OPERATOR_BUILD_TARBALL env not set"
  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="3scale-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##*/}

OUTPUT_DIR=$(dirname "${OPERATOR_BUILD_TARBALL}")
echo "$OUTPUT_DIR"
# Initialize OUTPUT_DIR
if [ -d "$OUTPUT_DIR" ]; then rm -Rf $OUTPUT_DIR; fi
mkdir -p ${OUTPUT_DIR}

# Download sources
curl -L ${TARBALL_URL} -o ${SOURCES_TARBALL}

# Extract sources
mkdir -p ${GOPATH_DIR}/src/${REPO_PATH}
tar -xzf ${SOURCES_TARBALL} -C ${GOPATH_DIR}/src/${REPO_PATH}
# Rename 3scale-operator-* directory to 3scale-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

# package vendor
tar -czf ${OPERATOR_BUILD_TARBALL} vendor
