#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"


die() {
    echo -e "Error: $1" >&2
    exit 1
}

MYARCH=$(uname -m)


"${SCRIPT_DIR}/build.sh" -m -r || die "Failed to build"

PUBLISH_DIR="${SCRIPT_DIR}/tool"
OUTPUT_DIR="${SCRIPT_DIR}/output"

# Find all dropshell-tool.ARCH files in output/
TOOLS=()
for tool in "${SCRIPT_DIR}/output/"/*dropshell-tool.*; do
    [ -f "$tool" ] || continue
    tool_name=$(basename "$tool")
    TOOLS+=("$tool_name")
done

if [ ${#TOOLS[@]} -eq 0 ]; then
    echo "No tools found in ${SCRIPT_DIR}/output/. Exiting."
    exit 1
fi

for TOOL in "${TOOLS[@]}"; do
    echo "Publishing $TOOL"

    # extract the architecture from the tool name
    ARCH="${TOOL//dropshell-tool./}"

    # copy the tool to the output/ directory
    cp "$OUTPUT_DIR/$TOOL" "$PUBLISH_DIR/dropshell-tool" || die "Failed to copy $TOOL to $PUBLISH_DIR/dropshell-tool"

    "$OUTPUT_DIR/dropshell-tool.${MYARCH}" publish "dropshell-tool:${ARCH}" "$PUBLISH_DIR" || die "Failed to publish $TOOL"

    # remove the tool from the output/ directory
    rm "$PUBLISH_DIR/dropshell-tool" || die "Failed to remove $PUBLISH_DIR/dropshell-tool"
done
