#!/usr/bin/env bash
# Sign DRG-XMRig release archives for the wallet's in-app updater (opt-in ed25519 signatures).
#
# The wallet verifies a detached ed25519 signature over the EXACT archive bytes against a public
# key pinned in src/util/xmrig_updater.h (kXmrigSignaturePublicKeyBase64). For each archive
# <name>.zip this produces <name>.zip.sig holding the base64 of the raw 64-byte ed25519 signature —
# upload that .sig next to the .zip as a release asset.
#
# Uses OpenSSL (>= 1.1.1) only — no Python/PyNaCl needed. OpenSSL's ed25519 is PureEdDSA (RFC 8032),
# the same primitive libsodium's crypto_sign_verify_detached checks, so signatures are compatible
# (verified by the wallet's unit tests + an interop check).
#
# Usage:
#   scripts/sign-xmrig-release.sh keygen [out-prefix]        # -> <prefix>.ed25519.{key,pub.b64}
#   scripts/sign-xmrig-release.sh pubkey <secret.key>        # print the base64 public key to pin
#   scripts/sign-xmrig-release.sh sign <secret.key> <file>...# -> <file>.sig per file
#
# Keep the secret key (.ed25519.key) OFFLINE. Paste the base64 public key into
# kXmrigSignaturePublicKeyBase64 in src/util/xmrig_updater.h.

set -euo pipefail
die() { echo "error: $*" >&2; exit 1; }
command -v openssl >/dev/null || die "openssl not found (need >= 1.1.1 with ed25519)"

# Raw 32-byte ed25519 public key (base64) from a private key file. The DER SubjectPublicKeyInfo for
# ed25519 is a fixed 12-byte prefix + the 32-byte key, so the trailing 32 bytes are the raw key.
pubkey_b64() { openssl pkey -in "$1" -pubout -outform DER | tail -c 32 | openssl base64 -A; }

cmd="${1:-}"; shift || true
case "$cmd" in
  keygen)
    prefix="${1:-drg-xmrig}"
    [ -e "$prefix.ed25519.key" ] && die "$prefix.ed25519.key already exists — refusing to overwrite"
    openssl genpkey -algorithm ed25519 -out "$prefix.ed25519.key"
    chmod 600 "$prefix.ed25519.key"
    pub="$(pubkey_b64 "$prefix.ed25519.key")"
    printf '%s\n' "$pub" > "$prefix.ed25519.pub.b64"
    echo "secret key : $prefix.ed25519.key   (KEEP OFFLINE, mode 600)"
    echo "public key : $prefix.ed25519.pub.b64"
    echo
    echo "Pin this in src/util/xmrig_updater.h (kXmrigSignaturePublicKeyBase64):"
    echo "  $pub"
    ;;
  pubkey)
    [ $# -ge 1 ] || die "usage: pubkey <secret.key>"
    pubkey_b64 "$1"
    ;;
  sign)
    [ $# -ge 2 ] || die "usage: sign <secret.key> <file>..."
    key="$1"; shift
    [ -f "$key" ] || die "no such key: $key"
    for f in "$@"; do
      [ -f "$f" ] || die "no such file: $f"
      raw="$(mktemp)"
      openssl pkeyutl -sign -inkey "$key" -rawin -in "$f" -out "$raw"
      openssl base64 -A -in "$raw" > "$f.sig"
      printf '\n' >> "$f.sig"
      rm -f "$raw"
      echo "signed: $f -> $f.sig"
    done
    echo "Upload each .sig as a release asset next to its archive."
    ;;
  *)
    die "usage: $0 {keygen [prefix] | pubkey <secret.key> | sign <secret.key> <file>...}"
    ;;
esac
