###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from SSLConfigRef import SSLConfigRef
from AuthMechanism import AuthMechanism
from LDAPUserRegistry import LDAPUserRegistry
from LocalOSUserRegistry import LocalOSUserRegistry
from CustomUserRegistry import CustomUserRegistry
from WIMUserRegistry import WIMUserRegistry
from UserRegistryRef import UserRegistryRef
from JAASAuthData import JAASAuthData

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('SecurityCommon')


  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':name }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", name);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereSecurityCommon");
  exportedObject.put("roleName", "WebSphereSecurityCommon");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.allowbasicauth", objid, "allowBasicAuth","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.uselocalsecurityserver", objid, "useLocalSecurityServer","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.usedomainqualifiedusernames", objid, "useDomainQualifiedUserNames","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.enabled", objid, "enabled","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.cachetimeout", objid, "cacheTimeout","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.enforcefinegrainedjcasecurity", objid, "enforceFineGrainedJCASecurity","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.enablejava2secruntimefiltering", objid, "enableJava2SecRuntimeFiltering","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.enforcejava2security", objid, "enforceJava2Security","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.allowallpermissionforapplication", objid, "allowAllPermissionForApplication","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.appenabled", objid, "appEnabled","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.dynamicallyupdatesslconfig", objid, "dynamicallyUpdateSSLConfig","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.activeprotocol", objid, "activeProtocol","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.internalserverid", objid, "internalServerId","SecurityCommon");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitycommon.issuepermissionwarning", objid, "issuePermissionWarning","SecurityCommon");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"SecurityCommon");

  extraObjects = AuthMechanism.exportAuthMechanisms(objid, respath, extraObjects, typeFolders, 'authMechanisms', "SecurityCommon");

  defaultSSLSettings = Util.getOptionalAttribute(objid, 'defaultSSLSettings', 'SecurityCommon');
  if defaultSSLSettings is not None and len(defaultSSLSettings) > 0:
    returndict = Util.createTypeFolder(respath, "SSLConfigRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, SSLConfigRef._export(defaultSSLSettings, currespath, "DefaultSSLSettings"));

  i = 0;
  jaasAuthDatas = Util.parseConfigIdListAttribute(objid, 'authDataEntries', "SecurityCommon");
  for jaasAuthData in jaasAuthDatas:
    if len(jaasAuthData) > 0:
      returndict = Util.createTypeFolder(respath, "JAASAuthData", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, JAASAuthData._export(jaasAuthData, currespath, Util.getRequiredAttribute(jaasAuthData, 'alias', 'JAASAuthData').replace("/","-")));
      i = i + 1;

  i = 0;
  ldapUserRegistries = LDAPUserRegistry.getLDAPUserRegistry(objid);
  for ldapUserRegistry in ldapUserRegistries:
    if len(ldapUserRegistry) > 0:
      returndict = Util.createTypeFolder(respath, "LDAPUserRegistry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, LDAPUserRegistry._export(ldapUserRegistry, currespath, "LDAP User Registry%s" % i));
      i = i + 1;

  i = 0;
  localOSUserRegistries = LocalOSUserRegistry.getLocalOSUserRegistry(objid);
  for localOSUserRegistry in localOSUserRegistries:
    if len(localOSUserRegistry) > 0:
      returndict = Util.createTypeFolder(respath, "LocalOSUserRegistry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, LocalOSUserRegistry._export(localOSUserRegistry, currespath, "Local OS User Registry%s" % i));
      i = i + 1;

  i = 0;
  customUserRegistries = CustomUserRegistry.getCustomUserRegistry(objid);
  for customUserRegistry in customUserRegistries:
    if customUserRegistry is not None and len(customUserRegistry) > 0:
      returndict = Util.createTypeFolder(respath, "CustomUserRegistry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, CustomUserRegistry._export(customUserRegistry, currespath, "Custom User Registry%s" % i));
      i = i + 1;

  i = 0;
  wimUserRegistries = WIMUserRegistry.getWIMUserRegistry(objid);
  for wimUserRegistry in wimUserRegistries:
    if wimUserRegistry is not None and len(wimUserRegistry) > 0:
      returndict = Util.createTypeFolder(respath, "WIMUserRegistry", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, WIMUserRegistry._export(wimUserRegistry, currespath, "WIM User Registry%s" % i));
      i = i + 1;

  activeUserRegistry = Util.getOptionalAttribute(objid, 'activeUserRegistry', 'SecurityCommon');
  if activeUserRegistry is not None and len(activeUserRegistry) > 0:
    returndict = Util.createTypeFolder(respath, "UserRegistryRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    type = "";
    if activeUserRegistry.find("#LDAPUserRegistry_") != -1:
      type = "LDAPUserRegistry";
    elif activeUserRegistry.find("#LocalOSUserRegistry_") != -1:
      type = "LocalOSUserRegistry";
    elif activeUserRegistry.find("#CustomUserRegistry_") != -1:
      type = "CustomUserRegistry";
    elif activeUserRegistry.find("#WIMUserRegistry_") != -1:
      type = "WIMUserRegistry";
    realm = "";
    realm = Util.getOptionalAttribute(activeUserRegistry, 'realm', "UserRegistry");
    Util.addAllFromExport(extraObjects, UserRegistryRef._export(activeUserRegistry, currespath, type, realm, type + " - " + realm));

  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('SecurityCommon');
  return result;


def create(parentid, jsonobject):
  Util.pushPathElement('SecurityCommon')
  if not jsonobject.has("roleProperties"):
    raise Exception("SecurityCommon resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "allowBasicAuth", roleProperties.optString("websphere.securitycommon.allowbasicauth", None));
  Util.addIfNotNone(properties, "useLocalSecurityServer", roleProperties.optString("websphere.securitycommon.uselocalsecurityserver", None));
  Util.addIfNotNone(properties, "useDomainQualifiedUserNames", roleProperties.optString("websphere.securitycommon.usedomainqualifiedusernames", None));
  Util.addIfNotNone(properties, "enabled", roleProperties.optString("websphere.securitycommon.enabled", None));
  Util.addIfNotNone(properties, "cacheTimeout", roleProperties.optString("websphere.securitycommon.cachetimeout", None));
  Util.addIfNotNone(properties, "enforceFineGrainedJCASecurity", roleProperties.optString("websphere.securitycommon.enforcefinegrainedjcasecurity", None));
  Util.addIfNotNone(properties, "enableJava2SecRuntimeFiltering", roleProperties.optString("websphere.securitycommon.enablejava2secruntimefiltering", None));
  Util.addIfNotNone(properties, "enforceJava2Security", roleProperties.optString("websphere.securitycommon.enforcejava2security", None));
  Util.addIfNotNone(properties, "allowAllPermissionForApplication", roleProperties.optString("websphere.securitycommon.allowallpermissionforapplication", None));
  Util.addIfNotNone(properties, "appEnabled", roleProperties.optString("websphere.securitycommon.appenabled", None));
  Util.addIfNotNone(properties, "dynamicallyUpdateSSLConfig", roleProperties.optString("websphere.securitycommon.dynamicallyupdatesslconfig", None));
  Util.addIfNotNone(properties, "activeProtocol", roleProperties.optString("websphere.securitycommon.activeprotocol", None));
  Util.addIfNotNone(properties, "internalServerId", roleProperties.optString("websphere.securitycommon.internalserverid", None));
  Util.addIfNotNone(properties, "issuePermissionWarning", roleProperties.optString("websphere.securitycommon.issuepermissionwarning", None));
  print "Creating SecurityCommon with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SecurityCommon", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('PropertyAttrs')) > -1):
        attName = 'properties';
      elif (foldername.find(Util.getTypeFoldername('AdditionalSecAttrs')) > -1):
        attName = 'additionalSecAttrs';
      elif (foldername.find(Util.getTypeFoldername('WebAuthAttrs')) > -1):
        attName = 'webAuthAttrs';
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if (propertyObject == 1):
        continue;
      authObject = AuthMechanism.createObjIfRole(objid, curjsonobject, currole);
      if (authObject == 1):
        continue;
      if currole == "WebSphereSSLConfigRef":
        SSLConfigRef.create(objid, curjsonobject, "defaultSSLSettings");
      elif currole == "WebSphereJAASAuthData":
        JAASAuthData.create(objid, curjsonobject);

  # Must create User Registries so that references can be created later
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereLDAPUserRegistry":
        LDAPUserRegistry.create(objid, curjsonobject);
      elif currole == "WebSphereLocalOSUserRegistry":
        LocalOSUserRegistry.create(objid, curjsonobject);
      elif currole == "WebSphereCustomUserRegistry":
        CustomUserRegistry.create(objid, curjsonobject);
      elif currole == "WebSphereWIMUserRegistry":
        WIMUserRegistry.create(objid, curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereUserRegistryRef":
        UserRegistryRef.doImport(objid, curjsonobject);
  Util.popPathElement('SecurityCommon');


def update(objid,jsonobject):
  Util.pushPathElement('SecurityCommon')
  if not jsonobject.has("roleProperties"):
    raise Exception("SecurityCommon resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.allowbasicauth", None), "allowBasicAuth","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.uselocalsecurityserver", None), "useLocalSecurityServer","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.usedomainqualifiedusernames", None), "useDomainQualifiedUserNames","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.enabled", None), "enabled","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.cachetimeout", None), "cacheTimeout","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.enforcefinegrainedjcasecurity", None), "enforceFineGrainedJCASecurity","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.enablejava2secruntimefiltering", None), "enableJava2SecRuntimeFiltering","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.enforcejava2security", None), "enforceJava2Security","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.allowallpermissionforapplication", None), "allowAllPermissionForApplication","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.appenabled", None), "appEnabled","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.dynamicallyupdatesslconfig", None), "dynamicallyUpdateSSLConfig","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.activeprotocol", None), "activeProtocol","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.internalserverid", None), "internalServerId","SecurityCommon");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securitycommon.issuepermissionwarning", None), "issuePermissionWarning","SecurityCommon");
  if len(atts) != 0:
    print "Modifying SecurityCommon with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "SecurityCommon configuration up to date.";

  Property.removeProperties(objid, 'properties',"SecurityCommon");
  Util.unsetAttribute(objid, "defaultSSLSettings", "SecurityCommon");

  jaasAuthDatas = Util.parseConfigIdListAttribute(objid, 'authDataEntries', "SecurityCommon");
  for jaasAuthData in jaasAuthDatas:
    if len(jaasAuthData) > 0:
      Util.remove(jaasAuthData);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('PropertyAttrs')) > -1):
        attName = 'properties';
      elif (foldername.find(Util.getTypeFoldername('AdditionalSecAttrs')) > -1):
        attName = 'additionalSecAttrs';
      elif (foldername.find(Util.getTypeFoldername('WebAuthAttrs')) > -1):
        attName = 'webAuthAttrs';
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if (propertyObject == 1):
        continue;
      authObject = AuthMechanism.updateObjIfRole(objid, curjsonobject, currole, "SecurityCommon");
      if (authObject == 1):
        continue;
      if currole == "WebSphereSSLConfigRef":
        SSLConfigRef.create(objid, curjsonobject, "defaultSSLSettings");
      elif currole == "WebSphereJAASAuthData":
        JAASAuthData.create(objid, curjsonobject);

  # Must create User Registries so that references can be created later
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereLDAPUserRegistry":
        LDAPUserRegistry.update(objid, curjsonobject);
      elif currole == "WebSphereLocalOSUserRegistry":
        LocalOSUserRegistry.update(objid, curjsonobject);
      elif currole == "WebSphereCustomUserRegistry":
        CustomUserRegistry.update(objid, curjsonobject);
      elif currole == "WebSphereWIMUserRegistry":
        WIMUserRegistry.update(objid, curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereUserRegistryRef":
        UserRegistryRef.doImport(objid, curjsonobject);
  Util.popPathElement('SecurityCommon');
