#!/bin/bash

set -euo pipefail

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


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

function publish_tool() {
    local TOOLPATH="$1"
    local TOOL;
    TOOL=$(basename "$TOOLPATH")

    echo "Publishing $TOOL to getbin.xyz"
    echo "(from $TOOLPATH)"

    "${TEMP_DIR}/sos" upload "getbin.xyz" "$TOOLPATH" "${TOOL}:latest"
}

function publish_executables() {
    OUTPUT_DIR="${SCRIPT_DIR}/output"

    # Find all dropshell-tool.ARCH files in output/
    TOOLS=()
    for tool in "${OUTPUT_DIR}"/*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
        publish_tool "$OUTPUT_DIR/$TOOL"
    done
}

function getbin() {
    local BIN_NAME="$1"
    
    curl -L -s -o "${TEMP_DIR}/${BIN_NAME}" "https://getbin.xyz/${BIN_NAME}" || die "Failed to download ${BIN_NAME}"
    chmod +x "${TEMP_DIR}/${BIN_NAME}"
}



getbin "sos"
publish_executables

rm -rf "${TEMP_DIR}"
echo "Done"