#!/usr/bin/env bash
# Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# For the build step concourse will set the following environment variables:
# SOURCE_PATH - path to component repository root directory.
# BINARY_PATH - path to an existing (empty) directory to place build results into.
if [[ -z "${SOURCE_PATH}" ]]; then
  export SOURCE_PATH="$(readlink -f $(dirname ${0})/..)"
else
  export SOURCE_PATH="$(readlink -f "${SOURCE_PATH}")"
fi

if [[ -z "${BINARY_PATH}" ]]; then
  export BINARY_PATH="${SOURCE_PATH}/bin"
else
  export BINARY_PATH="$(readlink -f "${BINARY_PATH}")/bin"
fi

VCS="github.com"
ORGANIZATION="gardener"
PROJECT="hvpa-controller"
REPOSITORY=${VCS}/${ORGANIZATION}/${PROJECT}

# The `go <cmd>` commands requires to see the target repository to be part of a
# Go workspace. Thus, if we are not yet in a Go workspace, let's create one
# temporarily by using symbolic links.
if [[ "${SOURCE_PATH}" != *"src/${REPOSITORY}" ]]; then
  SOURCE_SYMLINK_PATH="${SOURCE_PATH}/tmp/src/${REPOSITORY}"
  if [[ -d "${SOURCE_PATH}/tmp" ]]; then
    rm -rf "${SOURCE_PATH}/tmp"
  fi
  mkdir -p "${SOURCE_PATH}/tmp/src/${VCS}/${ORGANIZATION}"
  ln -s "${SOURCE_PATH}" "${SOURCE_SYMLINK_PATH}"
  cd "${SOURCE_SYMLINK_PATH}"

  export GOPATH="${SOURCE_PATH}/tmp"
  export GOBIN="${SOURCE_PATH}/tmp/bin"
  export PATH="${GOBIN}:${PATH}"
fi

###############################################################################

VERSION_FILE="$(readlink  -f "${SOURCE_PATH}/VERSION")"
VERSION="$(cat "${VERSION_FILE}")"
GIT_SHA=$(git rev-parse --short HEAD || echo "GitNotFound")

# If no LOCAL_BUILD environment variable is set, we configure the `go build` command
# to build for linux OS, amd64 architectures and without CGO enablement.
if [[ -z "$LOCAL_BUILD" ]]; then
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build \
    -a \
    -v \
    -mod=vendor \
    -o ${BINARY_PATH}/linux-amd64/manager \
    main.go

# If the LOCAL_BUILD environment variable is set, we simply run `go build`.
else
  GO111MODULE=on go build \
    -v \
    -mod=vendor \
    -o ${BINARY_PATH}/manager \
    main.go
fi