/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.test.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.TimeZone;

import javax.security.auth.x500.X500Principal;

import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey;

public class CertificateUtils {

    public static SelfSignedX509CertificateAndSigningKey generateSelfSignedCertificate() throws Exception {
        // generate certificate
        Date from = new Date();
        Date to = new Date(from.getTime() + (1000L * 60L * 60L * 24L * 365L * 10L));
        SelfSignedX509CertificateAndSigningKey selfSignedCertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder()
                .setDn(new X500Principal("CN=client"))
                .setNotValidAfter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(to.getTime()), TimeZone.getDefault().toZoneId()))
                .setNotValidBefore(ZonedDateTime.ofInstant(Instant.ofEpochMilli(from.getTime()), TimeZone.getDefault().toZoneId()))
                .setKeyAlgorithmName("RSA")
                .setKeySize(2048)
                .setSignatureAlgorithmName("SHA256withRSA")
                .build();
        return selfSignedCertificateAndSigningKey;
    }

    public static void generateTrustStore(X509Certificate cert, File storeFile, String type) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        KeyStore ts = KeyStore.getInstance(type);

        ts.load(null, "secret".toCharArray());

        ts.setCertificateEntry("client", cert);

        try (FileOutputStream fos = new FileOutputStream(storeFile)) {
            ts.store(fos, "secret".toCharArray());
        }
    }

    public static void generateKeyStore(SelfSignedX509CertificateAndSigningKey selfSignedCertificateAndSigningKey, File storeFile, String type) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        KeyStore ks = KeyStore.getInstance(type);

        ks.load(null, "secret".toCharArray());

        if (selfSignedCertificateAndSigningKey != null) {
            ks.setKeyEntry("client", selfSignedCertificateAndSigningKey.getSigningKey(), "secret".toCharArray(),
                    new X509Certificate[]{selfSignedCertificateAndSigningKey.getSelfSignedCertificate()});
        }

        try (FileOutputStream fos = new FileOutputStream(storeFile)) {
            ks.store(fos, "secret".toCharArray());
        }
    }
}
