package updater

import (
	"os/exec"
	"path/filepath"
	"testing"
)

// TestVerifyBlobSignatureWithOpenSSL is a confidence test for the
// smoke release-builder path: openssl's `dgst -sha256 -sign` produces
// the exact same encoding cosign emits for blob signatures (base64
// ASN.1 ECDSA over SHA256(body)). If this ever stops verifying, the
// smoke update scenarios will silently skip the signature check —
// catching it here avoids a heisenbug in scripts/smoke.sh.
func TestVerifyBlobSignatureWithOpenSSL(t *testing.T) {
	if _, err := exec.LookPath("openssl"); err != nil {
		t.Skip("openssl not on PATH")
	}
	dir := t.TempDir()
	keyPath := filepath.Join(dir, "cosign.key")
	pubPath := filepath.Join(dir, "cosign.pub")
	bodyPath := filepath.Join(dir, "body.txt")
	sigPath := filepath.Join(dir, "body.sig")

	mustRun := func(name string, args ...string) {
		t.Helper()
		out, err := exec.Command(name, args...).CombinedOutput()
		if err != nil {
			t.Fatalf("%s %v: %v\n%s", name, args, err, string(out))
		}
	}

	mustRun("openssl", "ecparam", "-name", "prime256v1", "-genkey", "-noout", "-out", keyPath)
	mustRun("openssl", "ec", "-in", keyPath, "-pubout", "-out", pubPath)
	mustRun("sh", "-c", "printf 'banger smoke release sums\n' > "+bodyPath)
	mustRun("sh", "-c", "openssl dgst -sha256 -sign "+keyPath+" "+bodyPath+" | base64 -w0 > "+sigPath)

	body := readFile(t, bodyPath)
	sig := readFile(t, sigPath)
	pub := readFile(t, pubPath)

	if err := VerifyBlobSignatureWithKey(body, sig, string(pub)); err != nil {
		t.Fatalf("VerifyBlobSignatureWithKey: %v", err)
	}
}

func readFile(t *testing.T, p string) []byte {
	t.Helper()
	out, err := exec.Command("cat", p).Output()
	if err != nil {
		t.Fatalf("read %s: %v", p, err)
	}
	return out
}
