package pbs

// ProbeFingerprint (PBS DR slice 2) — the verify-pin-BEFORE-consume check: a bare TLS dial to
// the PBS server pinned to the DESCRIPTOR's fingerprint. Success proves the box at that address
// presents exactly the pinned cert (and is reachable over the tunnel); nothing is authenticated
// and nothing is consumed. A mismatch or unreachability MUST abort the bridge before the
// one-time token secret is touched (the offsite ordering law).

import (
	"context"
	"crypto/tls"
	"fmt"
	"net"
	"strings"
	"time"
)

// ProbeFingerprint dials server (host or host:port; default port 8007) and verifies the
// presented leaf cert against fingerprint (sha256, colon-form ok). Returns nil only when the
// pin matches exactly.
func ProbeFingerprint(ctx context.Context, server, fingerprint string) error {
	tlsCfg, err := pinnedTLS(fingerprint)
	if err != nil {
		return err
	}
	addr := server
	if !strings.Contains(addr, ":") {
		addr = net.JoinHostPort(addr, "8007")
	}
	d := net.Dialer{Timeout: 15 * time.Second}
	raw, err := d.DialContext(ctx, "tcp", addr)
	if err != nil {
		return fmt.Errorf("pbs: fingerprint probe dial %s: %w", addr, err)
	}
	defer raw.Close()
	if dl, ok := ctx.Deadline(); ok {
		raw.SetDeadline(dl)
	} else {
		raw.SetDeadline(time.Now().Add(15 * time.Second))
	}
	conn := tls.Client(raw, tlsCfg)
	if err := conn.HandshakeContext(ctx); err != nil {
		return fmt.Errorf("pbs: fingerprint probe %s: %w", addr, err)
	}
	conn.Close()
	return nil
}
