#!/usr/bin/env bash

set -eu

if [ $# -ne 0 ]; then
    echo "no arguments allowed for ${0##*/}, given: $*" >&2
    exit 64
fi

bindir=$( cd "${BASH_SOURCE[0]%/*}" && pwd )
rootdir=$( cd "$bindir"/.. && pwd )

# shellcheck source=_docker.sh
. "$bindir"/_docker.sh
# shellcheck source=_tag.sh
. "$bindir"/_tag.sh

dockerfile=$rootdir/cli/Dockerfile

# shellcheck disable=SC2046
docker_build cli-bin "${TAG:-$(head_root_tag)}" "$dockerfile" \
    --build-arg LINKERD_VERSION="${TAG:-$(head_root_tag)}" \
    --target="$DOCKER_TARGET"

IMG=$(docker_repo cli-bin):${TAG:-$(head_root_tag)}
ID=$(docker create "$IMG")

# copy the newly built linkerd cli binaries to the local system
OS=$DOCKER_TARGET
if [ "$DOCKER_TARGET" = 'multi-arch' ]; then
  OS=$OS_ARCH_ALL
fi
for OS in $OS; do
  DIR=$rootdir/target/cli/$OS
  mkdir -p "$DIR"

  # only copy if available
  (docker cp "$ID:/out/linkerd-${OS}" "$DIR/linkerd" 2> /dev/null) && echo "$DIR/linkerd"
done

docker rm "$ID" >/dev/null
