#!/usr/bin/env bash
set -e

# ASIC Hub download and setup script

# Colors
RED="\033[0;31m"
YELLOW="\e[93m"
NC='\033[0m'

# Params
HUB_CHANNEL="${HUB_CHANNEL:-stable}"
HUB_BUILD="${HUB_BUILD:-latest}"
HUB_INSTALL_SCRIPT="./install.sh"
HUB_REPO_URL="${HUB_REPO_URL:-https://download.hiveos.farm/hub}"
HUB_VERSION_FILE="version.json"

is_user_root() { [ "${EUID:-$(id -u)}" -eq 0 ]; }
panic() {
	printf "${RED}ERROR:${NC} %s\n" "$*" >&2
	exit 1
}

warn() {
	printf "${YELLOW}WARNING:${NC} %s\n" "$*" >&2
}

hub_get_platform() {
	arch_name=$(uname -m)
	os_name=$(uname -s | awk '{print tolower($0)}')
	case ${arch_name} in
	"x86_64" | "amd64")
		echo "${os_name}-amd64"
		;;
	"i386" | "i486" | "i586")
		echo "${os_name}-386"
		;;
	"armv7l" | "arm" | "armhf")
		echo "${os_name}-arm"
		;;
	"aarch64" | "arm64")
		echo "${os_name}-arm64"
		;;
	*)
		panic "Unsupported platform: $arch_name"
		;;
	esac
}

hub_main() {
	local hub_platform
	hub_platform=$(hub_get_platform)
	local hub_file_name="hub-${hub_platform}.tar.gz"
	local hub_download_url="$HUB_REPO_URL/$HUB_CHANNEL/$HUB_BUILD/$hub_file_name"
	local hub_version_file="$HUB_REPO_URL/$HUB_CHANNEL/$HUB_BUILD/$HUB_VERSION_FILE"

	local hub_tempdir
	hub_tempdir=$(mktemp -d)
	local dest_file="$hub_tempdir/$hub_file_name"
	echo ":: Downloading ASIC Hub from '${hub_download_url}'..."
	if ! curl -S -L --fail --progress-bar -o "$dest_file" "$hub_download_url"; then
		rm -rf "$hub_tempdir"
		panic "Download failed. Try to download and install ASIC Hub manually: https://hiveos.farm/ASIC-Hub-installation-linux/"
	fi

	echo ":: Checking file hash..."
	local version_file="$hub_tempdir/$HUB_VERSION_FILE"
	if ! curl -s -L --fail -o "$version_file" "$hub_version_file"; then
		rm -rf "$hub_tempdir"
		panic "Failed to check MD5 hash sum. Try to download and install ASIC Hub manually: https://hiveos.farm/ASIC-Hub-installation-linux/"
	fi

	local expected_hash
	local got_hash
	local subs_expr
	# shellcheck disable=SC2016
	subs_expr=$(printf '/"%s":/,$p' "$hub_platform")
	expected_hash=$(sed -n "$subs_expr" "$version_file" | sed -rn 's/"md5": "([A-Za-z0-9]+)".*$/\1/p' | head -n 1 | sed -e 's/^[[:space:]]*//')
	got_hash=$(md5sum "$dest_file" | awk '{print $1}')

	if [[ "$expected_hash" != "$got_hash" ]]; then
		rm -rf "$hub_tempdir"
		panic "Invalid MD5 hash. Expected '$expected_hash' but got '$got_hash'"
	fi

	echo ":: Extracting install files..."
	cd "$hub_tempdir"
	tar -xf "$hub_file_name"

	echo ":: Installing ASIC Hub..."
	cd "hub-${hub_platform}"
	if ! is_user_root; then
		echo "> 🔒 Please enter your password to install ASIC Hub"
	fi
	if ! sudo "$HUB_INSTALL_SCRIPT" --yes; then
		rm -rf "$hub_tempdir"
		panic "Installation failed. Try to download and install ASIC Hub manually: https://hiveos.farm/ASIC-Hub-installation-linux/"
	fi

	rm -rf "$hub_tempdir"
	if [ -z "$FARM_HASH" ]; then
		exit 0
	fi

	if [[ ! "$FARM_HASH" =~ ^[a-fA-F0-9]{40}$ ]]; then
		warn "invalid farm hash format, skipping ASIC Hub registration."
		exit 0
	fi

	echo ":: Registering ASIC Hub with farm hash '$FARM_HASH'..."
	if ! /opt/asic-hub/hubctl register "$FARM_HASH"; then
		warn "failed to register ASIC Hub. Please register ASIC Hub manually from web interface."
	fi
}

hub_main
