#!/bin/bash

# Manage the manager-user's peer SSH keypair. One keypair per LibrePortal
# install — used as the *outbound* identity when this host SSHes into a
# direct-ssh peer, AND the public half is what other instances paste into
# their pairing wizard to authorize this host.
#
# Lives under ~/.ssh/libreportal-peer{,.pub} so it sits alongside the other
# manager keys without polluting id_rsa/id_ed25519.

_peerKeyDir()      { echo "${HOME}/.ssh"; }
_peerKeyPrivPath() { echo "$(_peerKeyDir)/libreportal-peer"; }
_peerKeyPubPath()  { echo "$(_peerKeyDir)/libreportal-peer.pub"; }

# Generate the keypair if it doesn't exist. Idempotent.
peerKeyEnsure()
{
    local dir; dir=$(_peerKeyDir)
    local priv; priv=$(_peerKeyPrivPath)
    local pub;  pub=$(_peerKeyPubPath)

    if [[ ! -d "$dir" ]]; then
        mkdir -p "$dir"
        chmod 700 "$dir"
    fi
    if [[ -f "$priv" && -f "$pub" ]]; then
        return 0
    fi

    isNotice "Generating LibrePortal peer keypair (one-time, ed25519)"
    ssh-keygen -t ed25519 -N '' -f "$priv" -C "libreportal-peer@${CFG_INSTALL_NAME:-$(hostname)}" >/dev/null 2>&1
    if [[ $? -ne 0 || ! -f "$priv" ]]; then
        isError "ssh-keygen failed — peer features unavailable"
        return 1
    fi
    chmod 600 "$priv"
    chmod 644 "$pub"
    isSuccessful "Peer keypair at $priv"
}

# Echo the local peer pubkey (one line). Empty if not generated yet.
peerKeyPublic()
{
    local pub; pub=$(_peerKeyPubPath)
    [[ -f "$pub" ]] || return 1
    cat "$pub"
}

# Echo the SHA256 fingerprint of the local peer key (matches ssh-keygen -l).
peerKeyFingerprint()
{
    local pub; pub=$(_peerKeyPubPath)
    [[ -f "$pub" ]] || return 1
    ssh-keygen -l -f "$pub" 2>/dev/null | awk '{print $2}'
}
