#!/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/image.sh
source $ROOT/hack/lib/registry.sh

function image::build::build_and_push() {
    lib::registry::login
    trap lib::registry::logout EXIT

    lib::registry::ensure_repo_exists ${@}

    for target in ${@}; do
        lib::image::get_image image $target
        # ACR enterprise edition sync fails on images with provenance attestation
        docker buildx build --push --provenance=false -t ${image} --platform ${VAR_PLATFORMS} -f ./build/${target}/Dockerfile .
    done
}

function image::build::build_only() {
    IFS=, read -ra platforms <<< "${VAR_PLATFORMS}"
    if [[ ${#platforms[@]} > 1 ]]; then
        echo "Now can only build for one platform"
        echo "Please see https://github.com/docker/buildx/issues/59"
        exit -1
    fi

    for target in ${@}; do
        lib::image::get_image image $target
        docker buildx build --provenance=false -t ${image} --platform ${VAR_PLATFORMS} -f ./build/${target}/Dockerfile .
    done
}

function run() {
    local targets
    local with_push=0
    while [[ $# -gt 0 ]]; do
        case $1 in
        --push)
            with_push=1
            shift
            ;;
        -*|--*)
            echo "Unknown option $1"
            exit 1
            ;;
        *)
            targets+=("$1") # save positional arg
            shift # past argument
            ;;
        esac
    done

    if [[ $with_push == 1 ]]; then
        image::build::build_and_push ${targets[@]}
    else
        image::build::build_only ${targets[@]}
    fi
}

run ${@}

