#!/bin/sh
# HiTechCloud Panel - installer bootstrap.
#
#   curl -sSL https://hitechcloud.org | bash -s -- [options]
#   bash INSTALL.sh [options]          (--help lists them)
#
# This stays a shell file for one reason: it is what an operator pipes from
# curl into a shell on a machine that has nothing installed yet. It does the
# least that needs: fetch the installer - hitechcloudcli, a Rust binary - for
# this machine's architecture from the mirror, check it against the release's
# SHA256SUMS, and hand over to `hitechcloudcli server-install` with the same
# arguments. Every step of the installation is in that command
# (hitechcloudcli/server/install.rs), and so are --dry-run, --adopt and
# --reinstall. HITECHCLOUD_MIRROR, HITECHCLOUD_VERSION (or --version) and
# HITECHCLOUD_INSTALLER (a hitechcloudcli already on this machine) say where
# the installer comes from.
set -eu
[ "$(id -u)" = 0 ] || { echo "Run as root: sudo bash INSTALL.sh" >&2; exit 1; }
[ -n "${HITECHCLOUD_INSTALLER:-}" ] && exec "$HITECHCLOUD_INSTALLER" --direct server-install "$@"
mirror="${HITECHCLOUD_MIRROR:-https://mirrors.hitechcloud.org}" release="${HITECHCLOUD_VERSION:-latest}" prev=""
for a in "$@"; do
    case "$prev" in --version) release="$a" ;; esac
    case "$a" in --version=*) release="${a#--version=}" ;; esac
    prev="$a"
done
case "$(uname -m)" in
    x86_64|amd64) arch=amd64 ;;
    aarch64|arm64) arch=arm64 ;;
    *) echo "Unsupported architecture: $(uname -m). The panel ships amd64 and arm64 builds." >&2; exit 1 ;;
esac
dir=$(mktemp -d) base="$mirror/releases/${release#v}" asset="hitechcloudcli-linux-$arch"
if ! curl -4fsSL --retry 3 --connect-timeout 20 "$base/$asset" -o "$dir/hitechcloudcli" ||
   ! curl -4fsSL --retry 3 --connect-timeout 20 "$base/SHA256SUMS" -o "$dir/SHA256SUMS"; then
    echo "Could not download the installer from $base - check this machine's DNS and outbound HTTPS." >&2
    rm -rf "$dir"; exit 1
fi
want=$(awk -v a="$asset" '$2 == a || $2 == "*"a { print $1; exit }' "$dir/SHA256SUMS")
if [ -z "$want" ] || [ "$want" != "$(sha256sum "$dir/hitechcloudcli" | cut -d' ' -f1)" ]; then
    echo "The installer does not match the release's SHA256SUMS. Nothing was installed." >&2
    rm -rf "$dir"; exit 1
fi
chmod 755 "$dir/hitechcloudcli"
HITECHCLOUD_BOOTSTRAP_DIR="$dir" exec "$dir/hitechcloudcli" --direct server-install "$@"
