package com.lingniu.ingest.inbound.mqtt.client;

import com.lingniu.ingest.inbound.mqtt.config.MqttInboundProperties;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.List;

public final class MqttTlsSupport {

    private MqttTlsSupport() {}

    public static SSLSocketFactory socketFactory(MqttInboundProperties.Tls tls) {
        try {
            KeyManager[] keyManagers = null;
            TrustManager[] trustManagers = null;
            if (tls != null && hasText(tls.getCaPem())) {
                trustManagers = trustManagerFactory(Path.of(tls.getCaPem())).getTrustManagers();
                if (!tls.isHostnameVerificationEnabled()) {
                    trustManagers = withoutHostnameVerification(trustManagers);
                }
            }
            if (tls != null && hasText(tls.getClientPem()) && hasText(tls.getClientKey())) {
                keyManagers = keyManagerFactory(Path.of(tls.getClientPem()), Path.of(tls.getClientKey())).getKeyManagers();
            }
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(keyManagers, trustManagers, null);
            SSLSocketFactory factory = context.getSocketFactory();
            if (tls != null && !tls.isHostnameVerificationEnabled()) {
                return new HostnameVerificationDisablingSocketFactory(factory);
            }
            return factory;
        } catch (Exception e) {
            throw new IllegalStateException("mqtt tls config build failed", e);
        }
    }

    private static TrustManagerFactory trustManagerFactory(Path caPem) throws Exception {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        int i = 0;
        for (Certificate cert : readCertificates(caPem)) {
            trustStore.setCertificateEntry("ca-" + i++, cert);
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        return tmf;
    }

    private static KeyManagerFactory keyManagerFactory(Path clientPem, Path clientKey) throws Exception {
        List<Certificate> chain = readCertificates(clientPem);
        PrivateKey key = readPrivateKey(clientKey);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        char[] password = new char[0];
        keyStore.setKeyEntry("mqtt-client", key, password, chain.toArray(Certificate[]::new));
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, password);
        return kmf;
    }

    private static List<Certificate> readCertificates(Path pem) throws Exception {
        String text = Files.readString(pem, StandardCharsets.UTF_8);
        List<Certificate> certificates = new ArrayList<>();
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        for (String block : pemBlocks(text, "CERTIFICATE")) {
            try (ByteArrayInputStream in = new ByteArrayInputStream(Base64.getMimeDecoder().decode(block))) {
                certificates.add(factory.generateCertificate(in));
            }
        }
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("no certificate found in " + pem);
        }
        return certificates;
    }

    private static PrivateKey readPrivateKey(Path pem) throws Exception {
        String text = Files.readString(pem, StandardCharsets.UTF_8);
        List<String> blocks = pemBlocks(text, "PRIVATE KEY");
        if (blocks.isEmpty()) {
            throw new IllegalArgumentException("no PKCS#8 private key found in " + pem);
        }
        byte[] der = Base64.getMimeDecoder().decode(blocks.getFirst());
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(der);
        return KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    private static List<String> pemBlocks(String text, String type) {
        String begin = "-----BEGIN " + type + "-----";
        String end = "-----END " + type + "-----";
        List<String> blocks = new ArrayList<>();
        int pos = 0;
        while (true) {
            int start = text.indexOf(begin, pos);
            if (start < 0) break;
            int contentStart = start + begin.length();
            int stop = text.indexOf(end, contentStart);
            if (stop < 0) break;
            blocks.add(text.substring(contentStart, stop).replaceAll("\\s+", ""));
            pos = stop + end.length();
        }
        return blocks;
    }

    private static boolean hasText(String value) {
        return value != null && !value.isBlank();
    }

    private static TrustManager[] withoutHostnameVerification(TrustManager[] managers) {
        TrustManager[] wrapped = new TrustManager[managers.length];
        for (int i = 0; i < managers.length; i++) {
            TrustManager manager = managers[i];
            if (manager instanceof X509TrustManager x509) {
                wrapped[i] = new ChainOnlyTrustManager(x509);
            } else {
                wrapped[i] = manager;
            }
        }
        return wrapped;
    }

    private static final class ChainOnlyTrustManager extends X509ExtendedTrustManager {
        private final X509TrustManager delegate;

        private ChainOnlyTrustManager(X509TrustManager delegate) {
            this.delegate = delegate;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket)
                throws CertificateException {
            if (delegate instanceof X509ExtendedTrustManager extended) {
                extended.checkClientTrusted(chain, authType, socket);
            } else {
                delegate.checkClientTrusted(chain, authType);
            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
                throws CertificateException {
            delegate.checkServerTrusted(chain, authType);
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
                throws CertificateException {
            if (delegate instanceof X509ExtendedTrustManager extended) {
                extended.checkClientTrusted(chain, authType, engine);
            } else {
                delegate.checkClientTrusted(chain, authType);
            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
                throws CertificateException {
            delegate.checkServerTrusted(chain, authType);
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            delegate.checkClientTrusted(chain, authType);
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            delegate.checkServerTrusted(chain, authType);
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return delegate.getAcceptedIssuers();
        }
    }

    private static final class HostnameVerificationDisablingSocketFactory extends SSLSocketFactory {
        private final SSLSocketFactory delegate;

        private HostnameVerificationDisablingSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }

        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }

        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

        @Override
        public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
            return prepare(delegate.createSocket(socket, host, port, autoClose));
        }

        @Override
        public Socket createSocket() throws IOException {
            return prepare(delegate.createSocket());
        }

        @Override
        public Socket createSocket(String host, int port) throws IOException {
            return prepare(delegate.createSocket(host, port));
        }

        @Override
        public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
            return prepare(delegate.createSocket(host, port, localHost, localPort));
        }

        @Override
        public Socket createSocket(InetAddress host, int port) throws IOException {
            return prepare(delegate.createSocket(host, port));
        }

        @Override
        public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
            return prepare(delegate.createSocket(address, port, localAddress, localPort));
        }

        private static Socket prepare(Socket socket) {
            if (socket instanceof SSLSocket sslSocket) {
                SSLParameters parameters = sslSocket.getSSLParameters();
                parameters.setEndpointIdentificationAlgorithm(null);
                sslSocket.setSSLParameters(parameters);
            }
            return socket;
        }
    }
}
