/*
 * 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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.apache.camel.quarkus.support.bouncycastle;

import java.lang.reflect.InvocationTargetException;
import java.security.Provider;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Cipher;

import io.quarkus.runtime.annotations.Recorder;
import io.quarkus.security.runtime.SecurityProviderUtils;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
import org.jboss.logging.Logger;

import static java.security.Security.addProvider;
import static java.security.Security.getProvider;

@Recorder
public class BouncyCastleRecorder {

    private static final Logger LOG = Logger.getLogger(BouncyCastleRecorder.class);

    public static final String BOUNCYCASTLE_PCQ_PROVIDER_NAME = "BCPCQ";

    public void registerBouncyCastleProvider(
            List<String> additionalProviders,
            List<String> cipherTransformations) {
        List<Provider> registeredProviders = new ArrayList<>();
        Provider provider = getProvider(SecurityProviderUtils.BOUNCYCASTLE_PROVIDER_NAME);
        if (provider == null) {
            provider = getProvider(SecurityProviderUtils.BOUNCYCASTLE_FIPS_PROVIDER_NAME);
        }
        if (provider == null) {
            // TODO: Fix BuildStep execution order so that this is not required
            // https://github.com/apache/camel-quarkus/issues/3472
            try {
                provider = (Provider) Thread.currentThread().getContextClassLoader()
                        .loadClass(SecurityProviderUtils.BOUNCYCASTLE_PROVIDER_CLASS_NAME).getConstructor().newInstance();
                addProvider(provider);
            } catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException
                    | NoSuchMethodException e) {
                try {
                    //try to load BCFIPS
                    provider = (Provider) Thread.currentThread().getContextClassLoader()
                            .loadClass(SecurityProviderUtils.BOUNCYCASTLE_FIPS_PROVIDER_CLASS_NAME).getConstructor()
                            .newInstance();
                    addProvider(provider);
                } catch (ClassNotFoundException | InvocationTargetException | InstantiationException | IllegalAccessException
                        | NoSuchMethodException e2) {
                    throw new RuntimeException("Neither BC nor BCFIPS provider can be registered. \nBC: " + e.getMessage()
                            + "\nBCFIPS " + e2.getMessage());
                }
            }
        }
        registeredProviders.add(provider);

        // Make it explicit to the static analysis that below security services should be registered as they are reachable at runtime
        for (String cipherTransformation : cipherTransformations) {
            try {
                LOG.debugf(
                        "Making it explicit to the static analysis that a Cipher with transformation %s could be used at runtime",
                        cipherTransformation);
                Cipher.getInstance(cipherTransformation, provider);
            } catch (Exception e) {
                // The cipher algorithm or padding is not present at runtime, a runtime error will be reported as usual
            }
        }

        if (additionalProviders.contains(BOUNCYCASTLE_PCQ_PROVIDER_NAME)) {
            Provider pqcProvider = getProvider("BCPQC");
            if (pqcProvider == null) {
                pqcProvider = new BouncyCastlePQCProvider();
                try {
                    addProvider(pqcProvider);
                } catch (SecurityException e) {
                    throw new RuntimeException(e);
                }
                LOG.debugf("Registered BouncyCastlePQCProvider");
            }
            registeredProviders.add(pqcProvider);

        }

    }
}
