#!/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 the ecs/vpc cni plugins from the submodules
# by copying them out of agent into their expected location in the
# gopath

set -ex

architecture=""
case $(uname -m) in
    x86_64)
	architecture="amd64"
        ;;
    arm64)
        architecture="arm64"
        ;;
    aarch64)
        architecture="arm64"
        ;;
    *)
        echo $"Unknown architecture $0"
        exit 1
esac

if [ "$architecture" == "amd64" ]; then export GOARCH=amd64; fi
if [ "$architecture" == "arm64" ]; then export GOARCH=arm64; fi

# this script assumes we've run the get-cni-sources make target to update the cni submodules
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

goversion=`go version | cut -d' ' -f3 | cut -c 3-`

export BUILDDIR="$(mktemp -d)"
export GITPATH="${BUILDDIR}/src/github.com/aws"
export GOPATH="${BUILDDIR}"

mkdir -p "${GITPATH}"
ln -s "${ROOT}/amazon-ecs-cni-plugins" "${GITPATH}"
ln -s "${ROOT}/amazon-vpc-cni-plugins" "${GITPATH}"

cd ${GITPATH}/amazon-ecs-cni-plugins && GO111MODULE=auto make plugins
mkdir -p ${ROOT}/misc/plugins && cp -a ./bin/plugins/. ${ROOT}/misc/plugins/
make clean

# buildvcs=false excludes version control information in golang >= 1.18. This is required for compiling agent with included repositories
if [[ $goversion < "1.18" ]]; then
	cd ${GITPATH}/amazon-vpc-cni-plugins && GO111MODULE=on GOFLAGS="-mod=vendor" make aws-appmesh vpc-branch-eni ecs-serviceconnect vpc-eni
else
	cd ${GITPATH}/amazon-vpc-cni-plugins && GO111MODULE=on GOFLAGS="-mod=vendor -buildvcs=false" make aws-appmesh vpc-branch-eni ecs-serviceconnect vpc-eni
fi
cp -a ./build/linux_${GOARCH}/. ${ROOT}/misc/plugins/
make clean
