package main

import (
	"crypto/tls"
	"fmt"
	"os"

	goPkcs12 "software.sslmate.com/src/go-pkcs12"
	stdPkcs12 "golang.org/x/crypto/pkcs12"
)

func main() {
	path := os.Args[1]
	pass := os.Args[2]

	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Printf("ERROR leyendo fichero: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("Fichero leído: %d bytes\n", len(data))

	// Intento 1: go-pkcs12 Decode (moderno)
	_, cert, err := goPkcs12.Decode(data, pass)
	if err != nil {
		fmt.Printf("go-pkcs12 Decode FALLO: %v\n", err)
	} else {
		fmt.Printf("go-pkcs12 Decode OK: subject=%s, expira=%s\n", cert.Subject.CommonName, cert.NotAfter.Format("2006-01-02"))
	}

	// Intento 2: go-pkcs12 Legacy
	cert2, err := goPkcs12.DecodeTrustStore(data, pass)
	if err != nil {
		fmt.Printf("go-pkcs12 DecodeTrustStore FALLO: %v\n", err)
	} else {
		fmt.Printf("go-pkcs12 DecodeTrustStore OK: %d certs\n", len(cert2))
	}

	// Intento 3: golang.org/x/crypto/pkcs12 (legacy)
	blocks, err := stdPkcs12.ToPEM(data, pass)
	if err != nil {
		fmt.Printf("x/crypto ToPEM FALLO: %v\n", err)
	} else {
		fmt.Printf("x/crypto ToPEM OK: %d bloques PEM\n", len(blocks))
	}

	// Intento 4: tls.X509KeyPair vía x/crypto
	if err == nil {
		var certPEM, keyPEM []byte
		for _, b := range blocks {
			if b.Type == "CERTIFICATE" {
				certPEM = append(certPEM, b.Bytes...)
			} else if b.Type == "PRIVATE KEY" {
				keyPEM = append(keyPEM, b.Bytes...)
			}
		}
		_ = tls.Certificate{}
		fmt.Printf("  cert PEM bytes: %d, key PEM bytes: %d\n", len(certPEM), len(keyPEM))
	}
}
