#!/usr/bin/env bash
# Installs and builds the QuBit One node and its mining tools on Ubuntu 24.04
# (Linux machine, or Ubuntu inside Windows with WSL2).
#
#   QBO_COMMIT=<hash> bash install-ubuntu.sh [branch]      (default branch: main)
#
# QBO_COMMIT (required) pins the code to one precise commit (the one announced with the release): if the
# repository or the account hosting it is hacked, the script refuses to build anything else.
# The hash must be complete (40 characters): a hash prefix of 7 or 8
# characters can be forged in a few minutes with a fake commit.
# Safe to run again: it updates the repository and rebuilds.
# Never creates a new key if ~/qbo-mining-key.json or ~/.qbo-address already exists.
set -euo pipefail

# Required, before anything else: the code comes from a public Radicle seed node, and a plain
# clone over the web does not check Aurel's signatures. Without the hash, any seed
# node (or whoever hacks it) would choose the code built here with sudo.
if [[ ! "${QBO_COMMIT:-}" =~ ^[0-9a-f]{40}$ ]]; then
  echo "set QBO_COMMIT=<complete hash of the commit given in the announcement (40 hexadecimal characters)>" >&2
  exit 1
fi

BRANCH="${1:-main}"
# The code is hosted on Radicle (peer-to-peer network, no account): any public seed node
# serves it through an ordinary web address. QBO_RID is the identifier of Aurel Thornquist's repository.
QBO_RID="${QBO_RID:-rad:zcrSDAg6DwgFLHEE8jkGDEFiZf5a}"
QBO_SEED="${QBO_SEED:-iris.radicle.network}"
REPO="${QBO_REPO:-https://$QBO_SEED/${QBO_RID#rad:}.git}"
SRC="$HOME/qubit-one"
KEYFILE="$HOME/qbo-mining-key.json"
VENV="$HOME/.qbo-venv"

echo "== System packages"
sudo apt-get update -q
sudo apt-get install -y -q build-essential cmake ninja-build pkgconf git python3-venv \
  libboost-dev libevent-dev libssl-dev
echo "== Source code ($BRANCH)"
if [[ -d "$SRC/.git" ]]; then
  git -C "$SRC" fetch -q origin "$BRANCH"
  git -C "$SRC" checkout -q "$BRANCH"
  git -C "$SRC" merge -q --ff-only "origin/$BRANCH"
else
  git clone -q --branch "$BRANCH" "$REPO" "$SRC"
fi
git -C "$SRC" checkout -q --detach "$QBO_COMMIT"
if [[ "$(git -C "$SRC" rev-parse HEAD)" != "$QBO_COMMIT" ]]; then
  echo "the code does not match the expected commit $QBO_COMMIT: stopping" >&2
  exit 1
fi
echo "commit built: $(git -C "$SRC" rev-parse HEAD) (compare it with the announced one)"

echo "== liboqs (ML-DSA-44 and SLH-DSA)"
if [[ ! -f /opt/liboqs/lib/liboqs.a ]]; then
  sudo "$SRC/node/contrib/qbo/build-liboqs.sh" /opt/liboqs
fi

echo "== Building the node (about ten minutes the first time)"
cmake -S "$SRC/node" -B "$SRC/build" -G Ninja -DCMAKE_PREFIX_PATH=/opt/liboqs -DCMAKE_BUILD_TYPE=Release \
  -DBUILD_GUI=OFF -DENABLE_WALLET=OFF -DENABLE_IPC=OFF -DWITH_ZMQ=OFF -DBUILD_TESTS=OFF -DBUILD_BENCH=OFF >/dev/null
# About 1.5 GB of memory per file compiled in parallel: WSL only has half of
# Windows' RAM, and Ninja would otherwise start as many compilations as threads.
JOBS=$(( $(awk '/MemTotal/ {print int($2 / 1572864)}' /proc/meminfo) ))
JOBS=$(( JOBS < 1 ? 1 : JOBS > $(nproc) ? $(nproc) : JOBS ))
cmake --build "$SRC/build" --target bitcoind bitcoin-cli -j "$JOBS"

echo "== Python (post-quantum signatures for the key)"
[[ -d "$VENV" ]] || python3 -m venv "$VENV"
"$VENV/bin/pip" install -q --require-hashes -r "$SRC/node/contrib/qbo/requirements-key.txt"

echo "== Mining key"
ADDRFILE="$HOME/.qbo-address"
if [[ -f "$KEYFILE" ]]; then
  echo "existing key kept: $KEYFILE (created on $(date -r "$KEYFILE" '+%Y-%m-%d'))"
  echo "  If it is an old test key, rename it (and ~/.qbo-address) then start again: a new key will be created."
  "$VENV/bin/python" "$SRC/node/contrib/qbo/qbokeygen.py" "$KEYFILE" --show > "$ADDRFILE"
elif [[ -s "$ADDRFILE" ]]; then
  # The key was stored away from the PC (recommended): keep the address, never a new key,
  # otherwise the rewards would go to a new key sitting on this PC.
  echo "existing address kept (key stored elsewhere): $(cat "$ADDRFILE") (written on $(date -r "$ADDRFILE" '+%Y-%m-%d'))"
  echo "  If it is the address of an old test key, rename ~/.qbo-address then start again."
else
  "$VENV/bin/python" "$SRC/node/contrib/qbo/qbokeygen.py" "$KEYFILE" >/dev/null
  echo "new key: $KEYFILE"
  echo "BACK IT UP NOW offline (encrypted USB stick, paper): whoever loses it loses their QBO."
  echo "Then remove it from this PC: mining only needs the address (~/.qbo-address), and malicious"
  echo "software on Windows can read Ubuntu's files (\\\\wsl\$). Only put it back to spend."
  "$VENV/bin/python" "$SRC/node/contrib/qbo/qbokeygen.py" "$KEYFILE" --show > "$ADDRFILE"
fi

echo "== Check on a local network"
LOG="$(mktemp --tmpdir qbo-test.XXXXXX.log)"
"$VENV/bin/python" "$SRC/node/contrib/qbo/mining_regtest.py" "$SRC/build/bin" >"$LOG" 2>&1 \
  && echo "the mining tools work" \
  || { echo "the test failed, see $LOG"; exit 1; }

echo
echo "Ready. Reward address: $(cat "$HOME/.qbo-address")"
echo "Start (pool for the Bitaxe): QBO_ADDNODE=<announced node, e.g. xxxx.onion:8833> QBO_BINDIR=$SRC/build/bin $SRC/node/contrib/qbo/qbo-launch.sh pool \$(cat ~/.qbo-address)"
