package main

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

func mainb() {
	var leaderPrivateKey *rsa.PrivateKey
	leaderPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal("Private key cannot be created.", err.Error())
	}

	// Generate a pem block with the private key
	keyPem := pem.EncodeToMemory(&pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(leaderPrivateKey),
	})

	tml := x509.Certificate{
		// you can add any attr that you need
		NotBefore: time.Now(),
		NotAfter:  time.Now().AddDate(5, 0, 0),
		// you have to generate a different serial number each execution
		SerialNumber: big.NewInt(123123),
		Subject: pkix.Name{
			CommonName:   "New Name",
			Organization: []string{"New Org."},
		},
		BasicConstraintsValid: true,
	}
	cert, err := x509.CreateCertificate(rand.Reader, &tml, &tml, &leaderPrivateKey.PublicKey, leaderPrivateKey)
	if err != nil {
		log.Fatal("Certificate cannot be created.", err.Error())
	}

	// Generate a pem block with the certificate
	certPem := pem.EncodeToMemory(&pem.Block{
		Type:  "CERTIFICATE",
		Bytes: cert,
	})

	tlsCert, err := tls.X509KeyPair(certPem, keyPem)
	if err != nil {
		log.Fatal("Cannot be loaded the certificate.", err.Error())
	}

	//listens for clients
	config := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
	lnClients, err := tls.Listen("tcp", ":4441", config)
	if err != nil {
		panic(err)
	}
	defer lnClients.Close()

	var pub rsa.PublicKey = leaderPrivateKey.PublicKey

	var network bytes.Buffer

	enc := gob.NewEncoder(&network)
	dec := gob.NewDecoder(&network)

	enc.Encode(pub)

	var pubRec rsa.PublicKey

	dec.Decode(&pubRec)

	fmt.Println(pub)
	fmt.Println(pubRec)

}
