#!/usr/bin/env bash

set -euo pipefail

usage() {
    echo "Usage: $0 <warm|verify> [bazel targets...]"
    echo
    echo "warm:   build targets normally so local results can upload to the remote cache"
    echo "verify: require all target actions to be available from remote cache"
}

if [ "$#" -lt 1 ]; then
    usage
    exit 2
fi

mode="$1"
shift

case "$mode" in
    warm | verify)
        ;;
    *)
        usage
        exit 2
        ;;
esac

tmp_root="${RUNNER_TEMP:-/private/tmp}"
run_id="${GITHUB_RUN_ID:-local}-$$"
output_user_root="${tmp_root%/}/eagle0-bazel-user-root-${run_id}"
output_base="${tmp_root%/}/eagle0-cache-parity-${mode}-${run_id}"

echo "Mode: $mode"
echo "Output user root: $output_user_root"
echo "Output base: $output_base"

run_ci_build_script() {
    local script="$1"
    shift

    echo "Build script: $script"
    echo "Build args:"
    printf '  %s\n' "$@"

    BAZEL_OUTPUT_USER_ROOT="$output_user_root" BAZEL_OUTPUT_BASE="$output_base" "$script" "$@"
}

cache_check_args() {
    local bazel_args=(
        "--remote_download_all"
    )

    if [ "$mode" = "verify" ]; then
        bazel_args+=(
            "--remote_upload_local_results=false"
            "--experimental_remote_require_cached"
            "--disk_cache="
        )
    fi

    printf '%s\n' "${bazel_args[@]}"
}

run_bazel_targets() {
    bazel_args=()
    while IFS= read -r arg; do
        bazel_args+=("$arg")
    done < <(cache_check_args)

    echo "Bazel args:"
    printf '  %s\n' "${bazel_args[@]}" "$@"

    bazel "--output_user_root=$output_user_root" "--output_base=$output_base" build "${bazel_args[@]}" "$@"
}

if [ "$#" -gt 0 ]; then
    run_bazel_targets "$@"
    exit 0
fi

bazel_args=()
while IFS= read -r arg; do
    bazel_args+=("$arg")
done < <(cache_check_args)
run_ci_build_script scripts/build_eagle_ci.sh "${bazel_args[@]}"
run_ci_build_script scripts/build_shardok_ci.sh "${bazel_args[@]}"
