package x509crt

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

func CreateCertKey(subject string, hostnames ...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)

	certSubject := pkix.Name{
		CommonName: subject,
	}
	certIssuer := certSubject

	dnsNames := make([]string, 0)
	dnsNames = append(dnsNames, subject)
	dnsNames = append(dnsNames, hostnames...)
	tml := x509.Certificate{
		SerialNumber:          big.NewInt(now.Unix()),
		NotBefore:             now,
		NotAfter:              now.AddDate(yearsAfter, 0, 0),
		Subject:               certSubject,
		Issuer:                certIssuer,
		DNSNames:              dnsNames,
		BasicConstraintsValid: true,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
		KeyUsage: x509.KeyUsageDigitalSignature |
			x509.KeyUsageContentCommitment |
			x509.KeyUsageKeyEncipherment |
			x509.KeyUsageDataEncipherment,
	}
	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 CreateCACert(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)

	certSubject := pkix.Name{
		CommonName: commonName,
	}
	certIssuer := certSubject

	tml := x509.Certificate{
		SerialNumber: big.NewInt(now.Unix()),
		NotBefore:    now,
		NotAfter:     now.AddDate(yearsAfter, 0, 0),
		Subject:      certSubject,
		Issuer:       certIssuer,
		IsCA:         true,
		ExtKeyUsage: []x509.ExtKeyUsage{
			x509.ExtKeyUsageClientAuth,
			x509.ExtKeyUsageServerAuth},
		KeyUsage: x509.KeyUsageDigitalSignature |
			x509.KeyUsageCertSign |
			x509.KeyUsageKeyEncipherment |
			x509.KeyUsageCRLSign,
		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
}
