/**
 * Copyright © 2012-2024 by Data Virtuality GmbH
 */
package org.teiid.core.util;

import org.teiid.core.TeiidRuntimeException;

import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * Utility class that should be used for proxy auth pre-validation.
 *
 * @author Anton Mogilchenko
 * @date 2024.12.10
 */
public class ProxyAuthUtil {

    public static final String JDK_AUTH_DISABLED_SCHEMES = "jdk.http.auth.tunneling.disabledSchemes";
    public static final String PROXY_AUTH_EXCEPTION = "Proxy authorization cannot be used because " +
            "\"%s\" Java system property is set to \"%s\". " +
            "Refer to our product documentation for more information.";
    private static final Properties netProperties;

    static {
        netProperties = getDefaultNetProperties();
    }

    public static void prevalidateProxyAuth(String username) throws TeiidRuntimeException {
        if (username == null)
            return;
        String disabledSchemes = System.getProperty(JDK_AUTH_DISABLED_SCHEMES) != null
                ? System.getProperty(JDK_AUTH_DISABLED_SCHEMES)
                : netProperties.getProperty(JDK_AUTH_DISABLED_SCHEMES);

        if (disabledSchemes != null && !disabledSchemes.trim().isEmpty())
            throw new TeiidRuntimeException(
                    String.format(PROXY_AUTH_EXCEPTION,
                            JDK_AUTH_DISABLED_SCHEMES,
                            disabledSchemes));
    }

    /**
     *
     * @return properties specified in JDK net.properties file
     */
    private static Properties getDefaultNetProperties() {
        Properties props = new Properties();
        Path path = Paths.get(System.getProperty("java.home"), "conf", "net.properties");

        try (Reader r = Files.newBufferedReader(path)) {
            props.load(r);
        } catch (IOException ignored) {}
        return props;
    }
}