#!/usr/bin/env bash

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

ROOT=$(cd $(dirname "${BASH_SOURCE[0]}")/../..; pwd -P)

# import golang vars
WITH_GOLANG=true
source $ROOT/hack/lib/vars.sh
source $ROOT/hack/lib/version.sh

function build::go::one() {
    local target=$1
    local os=$2
    local arch=$3

    local ldflags=$(lib::version::get_ldflags)

    cd ${ROOT}/cmd/${target}

    CGO_ENABLED=0 \
    GOPRIVATE=github.com/tidbcloud \
    GOCACHE="${VAR_GOCACHE}" \
    GOMODCACHE="${VAR_GOMODCACHE}" \
    GOPROXY="${VAR_GOPROXY}" \
    GOOS=${os} \
    GOARCH=${arch} \
    go build -v \
        -o ${ROOT}/bin/${os}/${arch}/${target} \
        -ldflags "${ldflags}" \
        main.go
}

function build::go::all() {
    local targets=${@:-"manager"}
    local platforms
    IFS=, read -ra platforms <<< "${VAR_PLATFORMS}"

    for target in ${targets}; do
        for platform in ${platforms[@]}; do
            case $platform in
            linux/arm64)
                build::go::one $target linux arm64 ;;
            linux/amd64)
                build::go::one $target linux amd64 ;;
            *)
                echo "unsupported platform ${platform}"
                exit 1
                ;;
            esac
        done
    done
}

build::go::all ${@}
