#!/bin/bash

set -o pipefail
#set -x
export PATH=$PATH:/usr/local/bin:/opt/homebrew/bin

if [[ "$1" = "-v" ]]; then
    exec depot --version
else

    params=("$@")

    # New array to hold modified parameters
    modified_params=()

    for param in "${params[@]}"; do
        if [[ $param == "build" ]]; then
            modified_params+=("build")
            if [[ "$DEPOT_WITH_LOAD" = "true" ]]; then
                modified_params+=("--load")
            fi
            if [[ "$DEPOT_WITH_SAVE" = "true" ]]; then
                modified_params+=("--save")
            fi
       else
            # Keep the parameter as is
            modified_params+=("$param")
        fi
    done

    # parse build id from the depot url that's printed
    # and rewrite it in Docker format so that pants docker backend
    # can parse it as image_id
    # See: https://github.com/pantsbuild/pants/blob/main/src/python/pants/backend/docker/goals/package_image.py#L519
    #
    # TODO: this can actually be implemented in a cleaner way by doing something like
    # depot build --save --metadata-file=build.json ….
    # Then parse the build ID out of the JSON file: $(cat build.json | jq -r .\[\"depot.build\"\].buildID)
    #
    tempfile=std.err
    1>$tempfile 2>&1 depot ${modified_params[@]}
    exit_code="$?"

    while IFS= read -r line; do
        1>&2 echo "$line"
    done <"$tempfile"

    if [[ "$exit_code" = "0" ]]; then
        # only check if command succeeded
        while IFS= read -r line; do
            if [[ $line =~ https://.+\/builds\/([a-zA-Z0-9]+) ]]; then
                echo 1>&2 "Successfully built ${BASH_REMATCH[1]}"
                break
            fi
        done <"$tempfile"
    fi
    exit $exit_code
fi
