#!/usr/bin/env bash
set -euo pipefail

release_base="${ROKO_RELEASE_BASE:-https://downloads.roko.network/releases/current}"
install_path="${ROKO_INSTALL_PATH:-/usr/local/bin/roko-node}"
dry_run=false

usage() {
  cat <<'EOF'
Usage: install-roko-native.sh [--dry-run]

Downloads the current architecture-specific ROKO testnet bundle, verifies it
against SHA256SUMS, and installs roko-node at /usr/local/bin/roko-node.

Environment overrides:
  ROKO_RELEASE_BASE  Artifact base URL
  ROKO_INSTALL_PATH Destination binary path
EOF
}

while (($#)); do
  case "$1" in
    --dry-run) dry_run=true ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
  shift
done

case "$(uname -m)" in
  x86_64) roko_arch=amd64 ;;
  aarch64|arm64) roko_arch=arm64 ;;
  *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

bundle="roko-node-testnet-linux-${roko_arch}.tar.gz"
echo "ROKO native installation"
echo "  architecture: ${roko_arch}"
echo "  bundle: ${release_base}/${bundle}"
echo "  destination: ${install_path}"

if "$dry_run"; then
  exit 0
fi

for command_name in curl sha256sum tar install mktemp; do
  command -v "$command_name" >/dev/null ||
    { echo "Missing required command: $command_name" >&2; exit 1; }
done

task_tmp="$(mktemp -d)"
cleanup() {
  rm -rf -- "$task_tmp"
}
trap cleanup EXIT

curl --fail --location --silent --show-error \
  "$release_base/$bundle" --output "$task_tmp/$bundle"
curl --fail --location --silent --show-error \
  "$release_base/SHA256SUMS" --output "$task_tmp/SHA256SUMS"

(
  cd "$task_tmp"
  sha256sum --check --ignore-missing SHA256SUMS
  tar -xzf "$bundle"
  test -x roko-node
  ./roko-node --version
)

if [[ "$(id -u)" -eq 0 ]]; then
  install -o root -g root -m 0755 "$task_tmp/roko-node" "$install_path"
elif command -v sudo >/dev/null; then
  sudo install -o root -g root -m 0755 "$task_tmp/roko-node" "$install_path"
else
  echo "Root access is required to install $install_path (sudo not found)." >&2
  exit 1
fi

"$install_path" --version
echo "Installed verified ROKO native binary at $install_path"
