#!/bin/sh -eu
# builds prod agent docker image
# eg `docker/agent.sh 1.2.3`
# eg `PUSH=1 docker/agent.sh latest`
push=${PUSH:-}
build=${BUILD:-$(date -u +%y%m%d$(test "$push" || echo "-%H%M%S"))}
git_version=$(git describe 2>/dev/null || echo 0.1.0)
version=${1:-$git_version}
tar=${TAR:-}

tags=''
if [ "$version" = latest ]; then
    version="${git_version%-*}"
    latest_version=$version
    while [ "$latest_version" != "${latest_version%.*}" ]; do
        latest_version=${latest_version%.*}
        tags="--tag procustodibus/agent:$latest_version $tags"
    done
    tags="--tag procustodibus/agent:latest $tags"
fi

if [ "$push" ]; then
    build_cmd="buildx build --push --platform linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6"
else
    build_cmd=build
fi


if [ ! "$tar" ]; then
    uv build --sdist
    tar=$(ls -1t dist/*.tar.gz | head -n1)
fi

docker $build_cmd \
    --build-arg AGENT_TAR=$tar \
    --build-arg AGENT_VERSION=$version \
    --build-arg IMAGE_BUILD=$build \
    $tags \
    --tag procustodibus/agent:$version \
    --tag procustodibus/agent:$version-i$build \
    --file docker/agent.dockerfile \
    .
