/*
	Licensed Material - Property of IBM

	(C) Copyright 2016 IBM Corp.

	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.
*/


'use strict';

var log = require('npmlog');

/**
 * Obtains CA certificate if needed
 *
 * Parameters:
 *
 * options = {
 *    ...
 *    port: <host-port>,
 *    protocol: <host-protocol>,
 *    ...
 * }
 *
 *  moduleName             // Mandatory String.  For sake of debugging
 *
 * Returns:
 *  Nothing. Options passed in will be updated accordingly
 *
 */
function getCertificate(options, moduleName) {
  log.level = global.MDO_CLI_LOG_LEVEL ? global.MDO_CLI_LOG_LEVEL : 'info';

  // Allow for an override of the CLI->server communication protocol argument
  // This override will allow for CLI->server communication over 'http' while maintaining
  // mobile client->server communication over 'https'.  This is a temporary hack
  // as the CLI does not completely support https.
  if (process.env.MFP_CLI_USE_HTTP && ('true' === process.env.MFP_CLI_USE_HTTP.toLocaleLowerCase())) {
    log.verbose(moduleName, 'Overriding protocol due to env MFP_CLI_USE_HTTP: http');
    options.protocol = 'http:';

    if (process.env.MFP_CLI_USE_HTTP_PORT) {
      log.verbose(moduleName, 'Overriding port due to env MFP_CLI_USE_HTTP_PORT: '+process.env.MFP_CLI_USE_HTTP_PORT);
      options.port = process.env.MFP_CLI_USE_HTTP_PORT;
    }
  }

  if (options.protocol === 'https:') {
    if (process.env.MFP_HTTPS_SSL_REJECT_UNAUTHORIZED && ('false' === process.env.MFP_HTTPS_SSL_REJECT_UNAUTHORIZED.toLocaleLowerCase())) {
      log.silly(moduleName, 'rejectUnauthorized = false');
      options.rejectUnauthorized = false;
    }

    // An array of authorized certificates can be provided.  The following code supports up to
    // 10 such certificates.  Set env vars in the format MFP_HTTPS_SSL_TRUSTSTORE_n, where n = 0-9.
    // with the value of the fully qualified path to a Base64 encoded certificate.
    //
    // Example: Using Java's keytool utility, export the Liberty server's self-generated, self-signed certificate
    // keytool -exportcert -keystore key.jks -storepass worklight -alias default -file keyjks-default.cer -rfc
    // (Windows)
    //     set MFP_HTTPS_SSL_TRUSTSTORE_0 = <full-path>\keyjks-default.cer
    // (server.xml) - confirm 'location', 'password', and 'serverKeyAlias' values
    //     <keyStore id="MyKeyStore" location="key.jks" type="JKS" password="worklight"/>
    //     <ssl id="MySSL" keyStoreRef="MyKeyStore" clientAuthenticationSupported="true" serverKeyAlias="default"/>
    //     <sslDefault sslRef="MySSL"/>
    var caArray = [];
    var fs = require('fs');
    for (var idx = 0; idx < 10; idx++) {
      log.silly(moduleName, 'Checking trust store env '+'MFP_HTTPS_SSL_TRUSTSTORE_'+idx);
      if (process.env['MFP_HTTPS_SSL_TRUSTSTORE_'+idx]) {
        try {
          log.silly(moduleName, 'Reading truststore: '+process.env['MFP_HTTPS_SSL_TRUSTSTORE_'+idx]);
          caArray.push(fs.readFileSync(process.env['MFP_HTTPS_SSL_TRUSTSTORE_'+idx]));
        }
        catch(err) {
          log.verbose(moduleName, 'Unable to read specified truststore: '+process.env['MFP_HTTPS_SSL_TRUSTSTORE_'+idx]+'; error = '+err);
        }
      }
    }

    // If no CA certificates supplied, then make sure the https 'ca' property is undefined; this
    // will cause node to use a "well known" list of CAs to validate the certificate
    options.ca = caArray.length > 0 ? caArray : undefined;
  }
}

module.exports = {
  getCertificate: getCertificate
};
