#!/usr/bin/env bash
# SIGIL lightnode + built-in dual-lane miner (ONE binary) — Hive OS installer
#   curl -fsSLk https://sigilgraph.fluxapp.xyz/downloads/install-sigil-top-hiveos.sh | bash
# (-k is safe: the tarball is verified against the SHA256 pinned below, not TLS.
#  Old rigs' CA stores don't trust the current Let's Encrypt chain, so plain
#  curl|bash fails SILENTLY there — always include -k on Hive OS.)
set -u
TARBALL_SHA256="942ff852c94ba32970b2407298a7e49193591619554fb8826e4bf73100d5a8d6"  # sigil-top-hiveos.tar.gz v7.1.0 glibc2.27 (pool shares)
URLS="https://sigilgraph.fluxapp.xyz/downloads/sigil-top-hiveos.tar.gz
https://sigilgraph.quillon.xyz/downloads/sigil-top-hiveos.tar.gz"
DEST="/hive/miners/custom"
echo "→ SIGIL sigil-top (lightnode + built-in dual-lane miner) · Hive OS installer"
[ -d "$DEST" ] || { echo "✗ $DEST missing — this doesn't look like a Hive OS rig"; exit 1; }
cd /tmp && rm -f sigil-top-hiveos.tar.gz
ok=""
for u in $URLS; do
  echo "  fetching $u"
  # normal TLS first, then insecure fallback (hash check below is the real gate)
  if curl -fSL --connect-timeout 15 "$u" -o sigil-top-hiveos.tar.gz 2>/dev/null \
  || curl -fSLk --connect-timeout 15 "$u" -o sigil-top-hiveos.tar.gz 2>/dev/null \
  || wget -q --timeout=15 "$u" -O sigil-top-hiveos.tar.gz 2>/dev/null \
  || wget -q --timeout=15 --no-check-certificate "$u" -O sigil-top-hiveos.tar.gz; then
    got=$(sha256sum sigil-top-hiveos.tar.gz | awk '{print $1}')
    if [ "$got" = "$TARBALL_SHA256" ]; then ok=1; break; fi
    echo "  ✗ hash mismatch from $u (got $got) — trying next mirror"
  else
    echo "  ✗ download failed from $u — trying next mirror"
  fi
done
[ -n "$ok" ] || { echo "✗ could not fetch a verified tarball from any mirror"; exit 1; }
echo "  ✓ SHA256 verified"
# Purge any previous install — Hive OS reuses an existing dir forever, so a stale
# (e.g. wrong-glibc) binary survives flight-sheet reinstalls unless removed here.
rm -rf "$DEST/sigil-top"
tar -xzf sigil-top-hiveos.tar.gz -C "$DEST"
chmod +x "$DEST/sigil-top/"*.sh "$DEST/sigil-top/sigil-top"
rm -f sigil-top-hiveos.tar.gz
VER=$(grep CUSTOM_VERSION "$DEST/sigil-top/h-manifest.conf" | cut -d= -f2)
echo "✓ installed sigil-top v$VER to $DEST/sigil-top"
echo "  → now RESTART the miner (Hive dashboard ⟳, or: miner restart) to load the new binary"
echo ""
echo "Flight sheet settings:"
echo "  Miner:            Custom"
echo "  Installation URL: https://sigilgraph.fluxapp.xyz/downloads/sigil-top-hiveos.tar.gz"
echo "  Miner name:       sigil-top"
echo "  Wallet template:  %WAL%   (64-hex SIGIL address — the wallet IS the pubkey, no KYC)"
echo "  Pool URL:         http://sigilgraph.quillon.xyz:8099   (sigil-rpcd)"
echo "  Extra config:     optional — 'SIGIL_MINE_CPU=1' to force CPU (default = GPU, auto CPU-fallback)"
echo ""
echo "ONE binary: node + light client + wallet + dual-lane miner (BLAKE4 Φ + VDF Ω)."
echo "⚠ testnet sigil-g0: coins are worthless by design and reset before mainnet."
