#!/bin/bash
#
# setup_signer_qube.sh — install nsigner v0.0.34+ and the qrexec bridge service
# in the nostr_signer qube.
#
# Run this in the nostr_signer qube (as the regular user, not root).
# It will:
#   1. Run install_nsigner.sh to download the latest nsigner release (v0.0.34+)
#   2. Install the qubes.NsignerRpc qrexec service (bridge mode)
#   3. Print instructions for starting the persistent signer
#
# Usage:
#   bash setup_signer_qube.sh

set -euo pipefail

NSIGNER_BIN="${HOME}/.local/bin/nsigner"
SERVICE_DST="/etc/qubes-rpc/qubes.NsignerRpc"

echo "=== n_signer qube setup ==="
echo

# Step 1: Update nsigner binary
if [ -f "${HOME}/install_nsigner.sh" ]; then
    echo "Step 1: Running install_nsigner.sh to update nsigner..."
    bash "${HOME}/install_nsigner.sh"
else
    echo "Step 1: install_nsigner.sh not found in ${HOME}."
    echo "  Make sure install_nsigner.sh is in your home directory first."
    exit 1
fi
echo

# Verify the bridge subcommand exists
echo "Verifying bridge subcommand..."
if ! "${NSIGNER_BIN}" bridge --help > /dev/null 2>&1; then
    echo "ERROR: nsigner does not have the 'bridge' subcommand."
    echo "  The installed version may be too old. Expected v0.0.34 or later."
    "${NSIGNER_BIN}" --version
    exit 1
fi
echo "OK: bridge subcommand available."
"${NSIGNER_BIN}" --version
echo

# Step 2: Install the qrexec service
echo "Step 2: Installing qrexec service to ${SERVICE_DST}..."
echo '#!/bin/sh' | sudo tee "${SERVICE_DST}" > /dev/null
echo '# qubes.NsignerRpc — stateless bridge to persistent nsigner unix socket' | sudo tee -a "${SERVICE_DST}" > /dev/null
echo '# No mnemonic, no secrets. Relays QREXEC_REMOTE_DOMAIN as source-qube preamble.' | sudo tee -a "${SERVICE_DST}" > /dev/null
echo "exec ${NSIGNER_BIN} bridge --to nsigner" | sudo tee -a "${SERVICE_DST}" > /dev/null
sudo chmod 0755 "${SERVICE_DST}"

echo "Service installed. Contents:"
cat "${SERVICE_DST}"
echo

echo "=== Signer qube setup complete ==="
echo
echo "To start the persistent signer (mnemonic entered at terminal, in mlock'd RAM):"
echo
echo "  ${NSIGNER_BIN} --listen unix --socket-name nsigner --bridge-source-trusted"
echo
echo "The signer will prompt you for the mnemonic. It stays running with the"
echo "mnemonic in RAM only — nothing on disk. Leave it running in a terminal."
echo
echo "Then from a caller qube (e.g. 'ai'):"
echo "  node examples/n_signer_qube_example_qrexec.js nostr_signer"
