import os

def set_provider_keys(private_key_path, public_key_path):
    # use system calls for openssl since PyOpenSSL doesn't expose the
    # necessary functions.
    if os.system('openssl version > /dev/null 2>&1') == 0:
        os.system('openssl genrsa -out %s 2048' % private_key_path)
        os.system('openssl rsa -in %s -pubout -out %s' % (private_key_path, public_key_path))


def get_metadata(cfg):
    prologue = """\
<?xml version="1.0"?>
<EntityDescriptor
    providerID="%(provider_id)s"
    xmlns="urn:liberty:metadata:2003-08">""" % cfg

    sp_head = """
  <SPDescriptor protocolSupportEnumeration="urn:liberty:iff:2003-08">"""

    signing_public_key = ''
    if cfg.has_key('signing_public_key') and cfg['signing_public_key']:
        if 'CERTIF' in cfg['signing_public_key']:
            signing_public_key = """
        <KeyDescriptor use="signing">
          <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <ds:X509Data><ds:X509Certificate>%s</ds:X509Certificate></ds:X509Data>
          </ds:KeyInfo>
        </KeyDescriptor>""" % cfg['signing_public_key']
        elif 'KEY' in cfg['signing_public_key']:
            signing_public_key = """
        <KeyDescriptor use="signing">
          <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <ds:KeyValue>%s</ds:KeyValue>
          </ds:KeyInfo>
        </KeyDescriptor>""" % cfg['signing_public_key']

    sp_body = """
    <AssertionConsumerServiceURL id="AssertionConsumerServiceURL1" isDefault="true">%(base_url)s/assertionConsumer</AssertionConsumerServiceURL>

    <SoapEndpoint>%(base_url)s/soapEndpoint</SoapEndpoint>

    <SingleLogoutServiceURL>%(base_url)s/singleLogout</SingleLogoutServiceURL>
    <SingleLogoutServiceReturnURL>%(base_url)s/singleLogoutReturn</SingleLogoutServiceReturnURL>
    <SingleLogoutProtocolProfile>http://projectliberty.org/profiles/slo-idp-http</SingleLogoutProtocolProfile>
    <SingleLogoutProtocolProfile>http://projectliberty.org/profiles/slo-sp-soap</SingleLogoutProtocolProfile>
    <SingleLogoutProtocolProfile>http://projectliberty.org/profiles/slo-sp-http</SingleLogoutProtocolProfile>

    <FederationTerminationServiceURL>%(base_url)s/federationTermination</FederationTerminationServiceURL>
    <FederationTerminationServiceReturnURL>%(base_url)s/federationTerminationReturn</FederationTerminationServiceReturnURL>
    <FederationTerminationNotificationProtocolProfile>http://projectliberty.org/profiles/fedterm-idp-soap</FederationTerminationNotificationProtocolProfile>
    <FederationTerminationNotificationProtocolProfile>http://projectliberty.org/profiles/fedterm-idp-http</FederationTerminationNotificationProtocolProfile>
    <FederationTerminationNotificationProtocolProfile>http://projectliberty.org/profiles/fedterm-sp-soap</FederationTerminationNotificationProtocolProfile>
    <FederationTerminationNotificationProtocolProfile>http://projectliberty.org/profiles/fedterm-sp-http</FederationTerminationNotificationProtocolProfile>

    <AuthnRequestsSigned>true</AuthnRequestsSigned>

  </SPDescriptor>""" % cfg

    orga = ''
    if cfg.get('organization_name'):
        orga = """
  <Organization>
    <OrganizationName>%s</OrganizationName>
  </Organization>""" % unicode(cfg['organization_name'], 'iso-8859-1').encode('utf-8')

    epilogue = """
</EntityDescriptor>"""

    return '\n'.join([prologue, sp_head, signing_public_key, sp_body, orga, epilogue])



def get_saml2_metadata(cfg):
    prologue = """\
<?xml version="1.0"?>
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    entityID="%(saml2_provider_id)s">""" % cfg

    sp_head = """
  <SPSSODescriptor
      AuthnRequestsSigned="true"
      protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">"""

    signing_public_key = ''
    if cfg.has_key('signing_public_key') and cfg['signing_public_key']:
        if 'CERTIF' in cfg['signing_public_key']:
            signing_public_key = """
        <KeyDescriptor use="signing">
          <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <ds:X509Data><ds:X509Certificate>%s</ds:X509Certificate></ds:X509Data>
          </ds:KeyInfo>
        </KeyDescriptor>""" % cfg['signing_public_key']
        elif 'KEY' in cfg['signing_public_key']:
            signing_public_key = """
        <KeyDescriptor use="signing">
          <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
            <ds:KeyValue>%s</ds:KeyValue>
          </ds:KeyInfo>
        </KeyDescriptor>""" % cfg['signing_public_key']

    sp_body = """
    <AssertionConsumerService isDefault="true" index="0"
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Artifact"
      Location="%(saml2_base_url)s/singleSignOnArtifact" />
    <SingleLogoutService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:SOAP"
      Location="%(saml2_base_url)s/singleLogoutSOAP" />
    <SingleLogoutService
      Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
      Location="%(saml2_base_url)s/singleLogout"
      ResponseLocation="%(saml2_base_url)s/singleLogoutReturn" />

  </SPSSODescriptor>""" % cfg
 
    orga = ''
    if cfg.get('organization_name'):
        orga = """
  <Organization>
    <OrganizationName>%s</OrganizationName>
  </Organization>""" % unicode(cfg['organization_name'], 'iso-8859-1').encode('utf-8')

    epilogue = """
</EntityDescriptor>"""

    return '\n'.join([prologue, sp_head, signing_public_key, sp_body, orga, epilogue])

