#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2014, 2015. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from TrustAssociation import TrustAssociation
from SingleSignon import SingleSignon
from DigestAuthentication import DigestAuthentication

__name_att__ = None;

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


  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 WebSphereKRB5");
  exportedObject.put("roleName", "WebSphereKRB5");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.trimusername", objid, "trimUserName","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.enabledgsscreddelegate", objid, "enabledGssCredDelegate","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.authconfig", objid, "authConfig","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.oid", objid, "OID","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.authvalidationconfig", objid, "authValidationConfig","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.krb5keytab", objid, "krb5Keytab","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.krb5spn", objid, "krb5Spn","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.simpleauthconfig", objid, "simpleAuthConfig","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.configured", objid, "configured","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.authcontextimplclass", objid, "authContextImplClass","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.krb5config", objid, "krb5Config","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.krb5realm", objid, "krb5Realm","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.allowltpaauth", objid, "allowLTPAAuth","KRB5");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.krb5.iscredentialforwardable", objid, "isCredentialForwardable","KRB5");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"KRB5");
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'KRB5');
  if trust is not None and len(trust) > 0:
    returndict = Util.createTypeFolder(respath, 'TrustAssociation', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, TrustAssociation._export(trust, currespath, "TrustAssociation"));

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

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

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

def doImportPartial(containmentpath, roleName, jsonobject):
  return doImport(containmentpath, roleName, jsonobject);

def doImport(containmentpath, roleName, jsonobject):

  krb5 = Util.getid(containmentpath);

  if krb5 == None or krb5 == "":
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      krb5 = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(krb5);
      krb5 = None;
    else:
      update(krb5, jsonobject);
  return krb5;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "trimUserName", roleProperties.optString("websphere.krb5.trimusername", None));
  Util.addIfNotNone(properties, "enabledGssCredDelegate", roleProperties.optString("websphere.krb5.enabledgsscreddelegate", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.krb5.authconfig", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.krb5.oid", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.krb5.authvalidationconfig", None));
  Util.addIfNotNone(properties, "krb5Keytab", roleProperties.optString("websphere.krb5.krb5keytab", None));
  Util.addIfNotNone(properties, "krb5Spn", roleProperties.optString("websphere.krb5.krb5spn", None));
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.krb5.simpleauthconfig", None));
  Util.addIfNotNone(properties, "configured", roleProperties.optString("websphere.krb5.configured", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.krb5.authcontextimplclass", None));
  Util.addIfNotNone(properties, "krb5Config", roleProperties.optString("websphere.krb5.krb5config", None));
  Util.addIfNotNone(properties, "krb5Realm", roleProperties.optString("websphere.krb5.krb5realm", None));
  Util.addIfNotNone(properties, "allowLTPAAuth", roleProperties.optString("websphere.krb5.allowltpaauth", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.krb5.iscredentialforwardable", None));
  print "Creating KRB5 with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("KRB5", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('KRB5');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.trimusername", None), "trimUserName","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.enabledgsscreddelegate", None), "enabledGssCredDelegate","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.authconfig", None), "authConfig","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.oid", None), "OID","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.authvalidationconfig", None), "authValidationConfig","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.krb5keytab", None), "krb5Keytab","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.krb5spn", None), "krb5Spn","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.simpleauthconfig", None), "simpleAuthConfig","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.configured", None), "configured","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.authcontextimplclass", None), "authContextImplClass","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.krb5config", None), "krb5Config","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.krb5realm", None), "krb5Realm","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.allowltpaauth", None), "allowLTPAAuth","KRB5");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.krb5.iscredentialforwardable", None), "isCredentialForwardable","KRB5");
  if len(atts) != 0:
    print "Modifying KRB5 with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"KRB5");
  digest = Util.getOptionalAttribute(objid, 'digestAuthentication', 'KRB5');
  if digest is not None and len(digest) > 0:
    Util.remove(digest);
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'KRB5');
  if trust is not None and len(trust) > 0:
    Util.remove(trust);
  sso = Util.getOptionalAttribute(objid, 'singleSignon', 'KRB5');
  if sso is not None and len(sso) > 0:
    Util.remove(sso);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('KRB5');
