#!/bin/bash
# Generated by release.yml (.github/scripts/legacy_update_sh.py).
# The migrations are hitechcloudcli update --migrate; see that script for why
# the compiled CLI is found before it is run.
set -u
bin_dir="${HITECHCLOUD_BIN_DIR:-/usr/local/bin}"
cli="${bin_dir}/hitechcloudcli"

is_elf() {
    local f
    f=$(readlink -f -- "$1" 2>/dev/null) || return 1
    [[ -f "$f" ]] || return 1
    [[ "$(head -c 4 -- "$f" | od -An -tx1 | tr -d ' \n')" == "7f454c46" ]]
}

if ! is_elf "$cli"; then
    old="${bin_dir}/hitechcloud-rustcli"
    if is_elf "$old"; then
        src=$(readlink -f -- "$old")
        install -m 755 -- "$src" "${cli}.new" && mv -f -- "${cli}.new" "$cli" || {
            echo "UPDATE.sh: could not install the compiled hitechcloudcli from $src over $cli" >&2
            exit 1
        }
        echo "UPDATE.sh: installed the compiled hitechcloudcli (from $old) over the script dispatcher"
    else
        echo "UPDATE.sh: no compiled hitechcloudcli on this server ($cli and $old are not binaries); run the 4.0.1 INSTALL.sh/update to fetch hitechcloudcli-linux-<arch>" >&2
        exit 1
    fi
fi
exec "$cli" --direct update --migrate "4.0.1"
