package tlsutil

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

func TestCertReloaderReload(t *testing.T) {
	dir := t.TempDir()
	certFile := filepath.Join(dir, "server.crt")
	keyFile := filepath.Join(dir, "server.key")

	if err := GenerateSelfSignedCert(certFile, keyFile); err != nil {
		t.Fatal(err)
	}
	reloader, err := NewCertReloader(certFile, keyFile)
	if err != nil {
		t.Fatal(err)
	}
	certA, err := reloader.GetCertificate(nil)
	if err != nil {
		t.Fatal(err)
	}

	// Overwrite with a fresh cert (delete first, since GenerateSelfSignedCert is
	// skip-if-exists).
	if err := os.Remove(certFile); err != nil {
		t.Fatal(err)
	}
	if err := os.Remove(keyFile); err != nil {
		t.Fatal(err)
	}
	if err := GenerateSelfSignedCert(certFile, keyFile); err != nil {
		t.Fatal(err)
	}
	if err := reloader.Reload(); err != nil {
		t.Fatal(err)
	}
	certB, err := reloader.GetCertificate(nil)
	if err != nil {
		t.Fatal(err)
	}

	if string(certA.Certificate[0]) == string(certB.Certificate[0]) {
		t.Fatal("expected Reload to pick up a different certificate, got the same bytes")
	}
}
