#!/bin/sh
set -eu

fail() {
    printf 'error: %s\n' "$*" >&2
    exit 1
}

version="${UINTELL_VERSION:-1.0.2}"
target="x86_64-unknown-linux-gnu"

case "$(uname -s)" in
    Linux) ;;
    *) fail "UIntellAgent currently supports Linux only" ;;
esac

case "$(uname -m)" in
    x86_64 | amd64) ;;
    *) fail "UIntellAgent currently supports x86-64 only" ;;
esac

case "$version" in
    1.0.2) expected_sha256="c8f36fe5bf7a263c24aa6e276ba7db2ca88f518a1a704e7ace4508b24fb48728" ;;
    *) fail "unsupported installer version: $version" ;;
esac

for command_name in curl tar sha256sum mktemp bash; do
    command -v "$command_name" >/dev/null 2>&1 || fail "$command_name is required"
done

base="uintell-agent-${version}-${target}"
archive_name="${base}.tar.gz"
release_url="https://github.com/uintell/uintellagent/releases/download/v${version}/${archive_name}"
temporary_dir="$(mktemp -d "${TMPDIR:-/tmp}/uintell-install.XXXXXX")" || fail "could not create a temporary directory"
cleanup() {
    rm -rf "$temporary_dir"
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM

printf 'Downloading UIntellAgent v%s...\n' "$version"
curl --proto '=https' --tlsv1.2 --fail --silent --show-error --location \
    --output "$temporary_dir/$archive_name" "$release_url"

actual_sha256="$(sha256sum "$temporary_dir/$archive_name")"
actual_sha256="${actual_sha256%% *}"
[ "$actual_sha256" = "$expected_sha256" ] || fail "release checksum verification failed"
printf 'Verified SHA-256: %s\n' "$actual_sha256"

tar -xzf "$temporary_dir/$archive_name" -C "$temporary_dir"
installer="$temporary_dir/$base/install.sh"
[ -x "$installer" ] || fail "the verified release archive does not contain its installer"

bash "$installer" --install

install_dir="${UINTELL_INSTALL_DIR:-${HOME:?HOME must be set}/.local/bin}"
printf '\nUIntellAgent v%s is installed.\n' "$version"
printf 'Next: %s/uintell-agent doctor\n' "$install_dir"
printf 'Run:  %s/uintell-agent --tui\n' "$install_dir"
