#!/bin/bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.

# This script builds a copy of the agent.
# It exists to wrap go build and properly make a static binary, as well as to
# correctly setup versioning before creating the binary

set -ex

# Pass in whether you want to build a static binary (true|false) and whether
# the resulting binary should be moved to an output directory
# The second option exists so that if built in a container, the result can be moved to a shared volume mount
# The thrid option is for skipping version generation when running cross-platform build, as it results in exec format error
static=${1:-true}
output_directory=${2:-}
version_gen=${3:-true}
with_pause=${4:-false}

PAUSE_CONTAINER_IMAGE="amazon/amazon-ecs-pause"
PAUSE_CONTAINER_TAG="0.1.0"

# Normalize to working directory being build root (up one level from ./scripts)
ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )
cd "${ROOT}"

# we need to make sure we've got the correct golang version installed
# if it's already installed the script will set env vars and exit
source ./scripts/install-golang.sh

# Set TARGET_OS from GOOS if it is not set
if [[ "${TARGET_OS}" == "" && "${GOOS}" != "" ]]; then
    TARGET_OS="${GOOS}"
fi

# setup temporary build directory
export TOPWD="$(pwd)"
export BUILDDIR="$(mktemp -d)"
export GOPATH="${BUILDDIR}"
export SRCPATH="${BUILDDIR}/src/github.com/aws"
mkdir -p "${SRCPATH}"

# create a gopath-friendly symlink to the BUILDROOT
# codebuild's path is TOPWD=/codebuild/output/src381519807/src/github.com/aws/amazon-ecs-agent/BUILDROOT
cd "${SRCPATH}"
ln -s "${TOPWD}" "amazon-ecs-agent"

# run build from our temporary linked srcpath
cd ${SRCPATH}/amazon-ecs-agent
if [[ "${version_gen}" == "true" ]]; then
    # We run the generator to setup the version and then always restore ourselves to a clean state
    cp agent/version/version.go agent/version/_version.go
    trap "cd \"${ROOT}\"; mv agent/version/_version.go agent/version/version.go" EXIT SIGHUP SIGINT SIGTERM

    cd ./agent/version/
    # Turn off go module here because version-gen.go is a separate program (i.e. "package main")
    # and no dependency needed to be fetched (but if go mod is on it will try to fetch dependency causing
    # this script to fail when we run it in a container with network mode "none").
    echo "running version gen"
    GO111MODULE=off go run gen/version-gen.go
fi

if [[ "${with_pause}" == "true" ]]; then
    LDFLAGS="-X github.com/aws/amazon-ecs-agent/agent/config.DefaultPauseContainerTag=$PAUSE_CONTAINER_TAG -X github.com/aws/amazon-ecs-agent/agent/config.DefaultPauseContainerImageName=$PAUSE_CONTAINER_IMAGE"
fi

if [ "${TARGET_OS}" == "windows" ]; then
    unset static
    build_artifact="out/amazon-ecs-agent.exe"
    export GOOS=windows
else
    build_artifact="out/amazon-ecs-agent"
fi

# run build from our temporary linked srcpath
cd ${SRCPATH}/amazon-ecs-agent
if [[ "${TARGET_OS}" == "windows" ]]; then
    go build -ldflags "${LDFLAGS} -s" -o $build_artifact ./agent/
elif [[ "${static}" == "true" ]]; then
    GO111MODULE=auto CGO_ENABLED=0 go build -installsuffix cgo -a -ldflags "${LDFLAGS} -s" -o $build_artifact ./agent/
else
    GO111MODULE=auto go build -o $build_artifact ./agent/
fi

if [[ -n "${output_directory}" ]]; then
    mv $build_artifact "${output_directory}"
fi

# finally, we'll clean up builddir
rm -r "${BUILDDIR}"
