#!/bin/bash
#
# setup_dom0.sh — install qrexec policy and tag the signer qube in dom0.
#
# Run this in dom0. It creates /etc/qubes/policy.d/40-nsigner.policy
# and tags the nostr_signer qube with 'nsigner-signer'.
#
# Usage:
#   bash setup_dom0.sh [signer_qube_name]
#
# Default signer qube name is "nostr_signer".

set -euo pipefail

SIGNER_QUBE="${1:-nostr_signer}"

echo "=== n_signer dom0 setup ==="
echo "Signer qube: ${SIGNER_QUBE}"
echo

# Create policy directory if it doesn't exist
sudo mkdir -p /etc/qubes/policy.d

# Write the qrexec policy
# The 'ai' qube is allowed without a dom0 popup (memory isolation is the
# real security boundary; the signer's own approval prompt is the gate).
# Any other qube gets a dom0 confirmation popup.
echo "Installing qrexec policy to /etc/qubes/policy.d/40-nsigner.policy..."
echo "# Qubes OS qrexec policy for nsigner" | sudo tee /etc/qubes/policy.d/40-nsigner.policy > /dev/null
echo "qubes.NsignerRpc * ai @tag:nsigner-signer allow target=${SIGNER_QUBE}" | sudo tee -a /etc/qubes/policy.d/40-nsigner.policy > /dev/null
echo "qubes.NsignerRpc * @anyvm @tag:nsigner-signer ask default_target=${SIGNER_QUBE}" | sudo tee -a /etc/qubes/policy.d/40-nsigner.policy > /dev/null
echo "qubes.NsignerRpc * @anyvm @anyvm deny" | sudo tee -a /etc/qubes/policy.d/40-nsigner.policy > /dev/null

echo "Policy installed. Contents:"
cat /etc/qubes/policy.d/40-nsigner.policy
echo

# Tag the signer qube
echo "Tagging ${SIGNER_QUBE} with 'nsigner-signer'..."
qvm-tags "${SIGNER_QUBE}" add nsigner-signer
echo "Tag added."
echo

# Verify
echo "=== Verification ==="
echo "Policy file:"
ls -l /etc/qubes/policy.d/40-nsigner.policy
echo
echo "Tags on ${SIGNER_QUBE}:"
qvm-tags "${SIGNER_QUBE}" list 2>/dev/null | grep nsigner || echo "(tag not found — check qube name)"
echo
echo "=== dom0 setup complete ==="
echo
echo "Next steps:"
echo "  1. In ${SIGNER_QUBE}: run setup_signer_qube.sh"
echo "  2. In ${SIGNER_QUBE}: start the persistent signer:"
echo "     ~/.local/bin/nsigner --listen unix --socket-name nsigner --bridge-source-trusted"
echo "  3. In caller qube: node examples/n_signer_qube_example_qrexec.js ${SIGNER_QUBE}"
