package me.proxylink.plugin.tls;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public final class SelfSignedCertificateGenerator {
    private static final SecureRandom SECURE_RANDOM = new SecureRandom();
    private static final String PROVIDER = "BC";
    private static final String ALIAS = "dirtsimplep2p";

    private SelfSignedCertificateGenerator() {
    }

    public static String createPkcs12(Path keyStorePath, char[] password, String nodeName)
            throws IOException, GeneralSecurityException {
        ensureProvider();
        Files.createDirectories(keyStorePath.toAbsolutePath().getParent());

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(3072, SECURE_RANDOM);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        Instant now = Instant.now();
        Date notBefore = Date.from(now.minus(1, ChronoUnit.DAYS));
        Date notAfter = Date.from(now.plus(3650, ChronoUnit.DAYS));
        BigInteger serial = new BigInteger(160, SECURE_RANDOM).abs();
        X500Name subject = new X500Name("CN=DirtSimpleP2P " + sanitizeCn(nodeName));

        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                subject,
                serial,
                notBefore,
                notAfter,
                subject,
                keyPair.getPublic()
        );

        ContentSigner signer;
        try {
            signer = new JcaContentSignerBuilder("SHA256withRSA")
                    .setProvider(PROVIDER)
                    .build(keyPair.getPrivate());
        } catch (OperatorCreationException e) {
            throw new GeneralSecurityException("Unable to create self-signed certificate signer", e);
        }
        X509CertificateHolder holder = builder.build(signer);
        X509Certificate certificate = new JcaX509CertificateConverter()
                .setProvider(PROVIDER)
                .getCertificate(holder);
        certificate.verify(keyPair.getPublic());

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(null, password);
        keyStore.setKeyEntry(ALIAS, keyPair.getPrivate(), password, new java.security.cert.Certificate[]{certificate});

        try (OutputStream output = Files.newOutputStream(keyStorePath)) {
            keyStore.store(output, password);
        }

        return CertificateFingerprints.sha256(certificate);
    }

    public static String fingerprintFromPkcs12(Path keyStorePath, char[] password)
            throws IOException, GeneralSecurityException {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (java.io.InputStream input = Files.newInputStream(keyStorePath)) {
            keyStore.load(input, password);
        }
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(ALIAS);
        if (certificate == null) {
            throw new GeneralSecurityException("Keystore does not contain certificate alias " + ALIAS);
        }
        return CertificateFingerprints.sha256(certificate);
    }

    private static void ensureProvider() {
        if (Security.getProvider(PROVIDER) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    private static String sanitizeCn(String value) {
        return value == null ? "node" : value.replace(",", "_").replace("=", "_");
    }
}
