#!/bin/sh
# Heimdall self-update.
#
# Safe to run from INSIDE a running Heimdall: curl -o onto a running binary
# fails with ETXTBSY, so this downloads beside it and renames over the top.
# A rename unlinks the old inode rather than writing into it, which the
# running process does not notice.
#
#   curl -fsSL https://s3.swervx.net/builds/heimdall-poc/latest/update.sh | sh
set -eu

BASE="https://s3.swervx.net/builds/heimdall-poc/latest"
DEST="${HEIMDALL_DIR:-$(pwd)}"

fetch() {
    name="$1"
    printf '  %-22s' "$name"
    if curl -fsSL "${BASE}/${name}" -o "${DEST}/${name}.new"; then
        chmod +x "${DEST}/${name}.new"
        mv -f "${DEST}/${name}.new" "${DEST}/${name}"
        printf 'ok\n'
    else
        rm -f "${DEST}/${name}.new"
        printf 'SKIPPED (not published)\n'
        return 1
    fi
}

echo "Updating Heimdall in ${DEST}"
fetch heimdall-poc
fetch heimdall-rdp-worker || true
fetch heimdall-poc-bridge || true

echo
echo "Done. Restart Heimdall to pick it up."
