package nxm.sys.intr;

import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.SSLUtilities;

/**
 * Provides a NeXtMidas command-line interface for
 * {@code SSLUtilities.initSSLContext(..)}.
 * @author Jeanette McCall
 * @author J. Czechowski
 * @since NextMidas 3.7.3 (Note: This command first appeared in the NeXtMidas
 * 3.7.2 release as a "hidden" command.  However, major changes were made
 * before the NeXtMidas 3.7.3 release where it was first considered part of
 * the "public" API for NeXtMidas.)
 */
public class Sslconfigure extends Intrinsic {

  /** default constructor */
  public Sslconfigure () {}

  public int open() {
    String propsFile   = MA.getCS("PROPSFILE",    null);
    String privKeyFile = MA.getCS("PRIVKEYFILE",  null);
    String passwd      = MA.getCS("PASSWORD",     null);
    String passwdFile  = MA.getCS("PASSWORDFILE", null);
    SSLUtilities.setNssLibsDir(MA.getCS("NSSLIBSDIR", null)); // Added for custom nss library directory since 3.9.1
    String label = MA.getU("LABEL",null);
    boolean insecure = MA.getState("/INSECURE", MA.find("/INSECURE")); // since 3.9.0
    boolean noHostNameVerification = MA.getState("/ANYHOSTNAME", MA.find("/ANYHOSTNAME")); // since 3.9.2 for NXM-3458
    String userDN = null;

    // 4.0.0 InternalUseOnly for testing where message size or certificate chain is large
    boolean enlargeJdkTlsMaxs = MA.getState("/BIGTLSMAX", MA.find("/BIGTLSMAX"));
    if (enlargeJdkTlsMaxs) {
      System.setProperty("jdk.tls.maxHandshakeMessageSize", "60000");
      System.setProperty("jdk.tls.maxCertificateChainLength", "70");
    }

    if (insecure) {
      // This is a trusts all hosts mode added for InternalUseOnly in 3.9.0
      boolean propsForUser = MA.getState("/PROPSFORUSER", MA.find("/PROPSFORUSER")); // 4.0.0
      if (!propsForUser && (propsFile==null)) {
        userDN = SSLUtilities.initInsecureSSL(M, privKeyFile, passwd, passwdFile);
      }
      else {
        userDN = SSLUtilities.initInsecureSSL(M, privKeyFile, passwd, passwdFile, propsFile, true);
      }
    }
    else if (noHostNameVerification) {
      // makes sure certificate is signed and not expired, but does not validate that host name matches - since 3.9.2 for NXM-3458
      userDN = SSLUtilities.initAnyHostNameSSL(M,null,propsFile,privKeyFile,passwd,
          passwdFile,null,null);
    }
    else {

      if (MA.find("PWDFILE")) {
        // PWDFILE= was only used in NeXtMidas 3.7.2
        M.deprecate("Use of PWDFILE= is deprecated, use PASSWORDFILE=");
      }

      userDN = SSLUtilities.initSSLContext(M,null,propsFile,privKeyFile,passwd,
          passwdFile,null,null);

    }

    if ((label != null) && !label.isEmpty()) {
      MR.put(label, userDN);
    }

    if (verbose) {
      M.info("SSLCONFIGURE: Configuration complete for "+userDN);
    }

    return FINISH;
  }

}
