package aux509

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"time"
)

func CreateX509SelfSignedCert(commonName string) ([]byte, []byte, error) {
	var err error
	certPem := make([]byte, 0)
	keyPem := make([]byte, 0)

	now := time.Now()

	const yearsAfter int = 10
	const keySize int = 2048

	key, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		err := fmt.Errorf("Can't create a private key: %v", err)
		return certPem, keyPem, err

	}
	keyPemBlock := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	keyPem = pem.EncodeToMemory(&keyPemBlock)

	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject: pkix.Name{
			CommonName: commonName,
		},
		DNSNames:              []string{commonName},
		BasicConstraintsValid: true,
	}
	certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
	if err != nil {
		return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)

	}
	certPemBlock := pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	}
	certPem = pem.EncodeToMemory(&certPemBlock)
	if err != nil {
		return certPem, keyPem, err
	}
	return certPem, keyPem, err
}

func CreateX509CACert(commonName string) ([]byte, []byte, error) {
	var err error
	certPem := make([]byte, 0)
	keyPem := make([]byte, 0)

	now := time.Now()

	const yearsAfter int = 10
	const keySize int = 2048

	key, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		err := fmt.Errorf("Can't create a private key: %v", err)
		return certPem, keyPem, err

	}
	keyPemBlock := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	keyPem = pem.EncodeToMemory(&keyPemBlock)

	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject: pkix.Name{
			CommonName: commonName,
		},
		IsCA:                  true,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
		BasicConstraintsValid: true,
	}
	certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, key)
	if err != nil {
		return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)

	}
	certPemBlock := pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	}
	certPem = pem.EncodeToMemory(&certPemBlock)

	if err != nil {
		return certPem, keyPem, err
	}
	return certPem, keyPem, err
}

func CreateX509Cert(commonName string, caKeyPem []byte, dnsNames ...string) ([]byte, []byte, error) {
	var err error
	certPem := make([]byte, 0)
	keyPem := make([]byte, 0)
	now := time.Now()

	const yearsAfter int = 10
	const keySize int = 2048

	key, err := rsa.GenerateKey(rand.Reader, keySize)
	if err != nil {
		err := fmt.Errorf("Can't create a private key: %v", err)
		return certPem, keyPem, err
	}
	keyPemBlock := pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}
	keyPem = pem.EncodeToMemory(&keyPemBlock)

	pemBlock, _ := pem.Decode(caKeyPem)
	if pemBlock == nil {
		err := fmt.Errorf("Can't parse a CA private key block")
		return certPem, keyPem, err
	}
	caKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
	if err != nil {
		err := fmt.Errorf("Can't parse a CA private key")
		return certPem, keyPem, err
	}

	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject: pkix.Name{
			CommonName: commonName,
		},
		DNSNames:              append([]string{commonName}, dnsNames...),
		IsCA:                  false,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		KeyUsage:              x509.KeyUsageDigitalSignature,
		BasicConstraintsValid: true,
	}
	certBytes, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &key.PublicKey, caKey)
	if err != nil {
		return certPem, keyPem, fmt.Errorf("Can't create a certificate: %v", err)

	}
	certPemBlock := pem.Block{
		Type:  "CERTIFICATE",
		Bytes: certBytes,
	}
	certPem = pem.EncodeToMemory(&certPemBlock)
	if err != nil {
		return certPem, keyPem, err
	}
	return certPem, keyPem, err
}
