# Path: pki/helper.py
# def subject_for_object(obj):
#     """Return a subject string.
#     
#     A OpenSSL compatible subject string is returned.
#     """
#     
#     subj = '/CN=%s/C=%s/ST=%s/localityName=%s/O=%s' % ( obj.common_name,
#                                                         obj.country,
#                                                         obj.state,
#                                                         obj.locality,
#                                                         obj.organization,
#                                                       )
#     
#     if obj.OU:
#         subj += '/organizationalUnitName=%s' % obj.OU
#     
#     if obj.email:
#         subj += '/emailAddress=%s' % obj.email
#     
#     return subj
# 
# Path: pki/settings.py
# PKI_OPENSSL_BIN = getattr(settings, 'PKI_OPENSSL_BIN', '/usr/bin/openssl')
# 
# PKI_OPENSSL_CONF = getattr(settings, 'PKI_OPENSSL_CONF', os.path.join(PKI_DIR, 'openssl.conf'))
# 
# PKI_DIR = getattr(settings, 'PKI_DIR', os.path.join(PKI_APP_DIR, 'PKI'))
# 
# PKI_OPENSSL_TEMPLATE = getattr(settings, 'PKI_OPENSSL_TEMPLATE', 'pki/openssl.conf.in')
# 
# PKI_SELF_SIGNED_SERIAL = getattr(settings, 'PKI_SELF_SIGNED_SERIAL', 0x0)
# 
# PKI_CA_NAME_BLACKLIST = ('_SELF_SIGNED_CERTIFICATES',)


import os
import re
import string
import random
import pki.models
from subprocess import Popen, PIPE, STDOUT
from shutil import rmtree
from logging import getLogger
from django.template.loader import render_to_string
from pki.helper import subject_for_object
from pki.settings import PKI_OPENSSL_BIN, PKI_OPENSSL_CONF, PKI_DIR, PKI_OPENSSL_TEMPLATE, \
                         PKI_SELF_SIGNED_SERIAL, PKI_CA_NAME_BLACKLIST
    from hashlib import md5 as md5_constructor
    from md5 import new as md5_constructor
        
        x509_list =[]
        for x509 in pki.models.x509Extension.objects.all():
            if x509.is_ca():
                x509.ca = True
            else:
                x509.ca = False
            x509_list.append(x509)
        
        # render template and save result to openssl.conf
        conf = render_to_string(PKI_OPENSSL_TEMPLATE, {'ca_list': ca_list, 'x509_extensions': x509_list,})
        
        f = open(PKI_OPENSSL_CONF, 'wb')
        f.write(conf)
        f.close()
    except Exception, e:
        logger.exception("Refreshing PKI metadata failed: %s" % e)
    
    logger.info("Successfully finished PKI metadata refresh")

class Openssl():
    """OpenSSL command and task wrapper class
    
    instance must be a CertificateAuthority or Certificate object.
    """
    
    def __init__(self, instance):
        """Initialize shared varaibles and verify instance type"""
        
        self.i    = instance

# Path: pki/helper.py
# def subject_for_object(obj):
#     """Return a subject string.
#     
#     A OpenSSL compatible subject string is returned.
#     """
#     
#     subj = '/CN=%s/C=%s/ST=%s/localityName=%s/O=%s' % ( obj.common_name,
#                                                         obj.country,
#                                                         obj.state,
#                                                         obj.locality,
#                                                         obj.organization,
#                                                       )
#     
#     if obj.OU:
#         subj += '/organizationalUnitName=%s' % obj.OU
#     
#     if obj.email:
#         subj += '/emailAddress=%s' % obj.email
#     
#     return subj
# 
# Path: pki/settings.py
# PKI_OPENSSL_BIN = getattr(settings, 'PKI_OPENSSL_BIN', '/usr/bin/openssl')
# 
# PKI_OPENSSL_CONF = getattr(settings, 'PKI_OPENSSL_CONF', os.path.join(PKI_DIR, 'openssl.conf'))
# 
# PKI_DIR = getattr(settings, 'PKI_DIR', os.path.join(PKI_APP_DIR, 'PKI'))
# 
# PKI_OPENSSL_TEMPLATE = getattr(settings, 'PKI_OPENSSL_TEMPLATE', 'pki/openssl.conf.in')
# 
# PKI_SELF_SIGNED_SERIAL = getattr(settings, 'PKI_SELF_SIGNED_SERIAL', 0x0)
# 
# PKI_CA_NAME_BLACKLIST = ('_SELF_SIGNED_CERTIFICATES',)


# Path: pki/openssl.py
import os
import re
import string
import random
import pki.models
from subprocess import Popen, PIPE, STDOUT
from shutil import rmtree
from logging import getLogger
from django.template.loader import render_to_string
from pki.helper import subject_for_object
from pki.settings import PKI_OPENSSL_BIN, PKI_OPENSSL_CONF, PKI_DIR, PKI_OPENSSL_TEMPLATE, \
                         PKI_SELF_SIGNED_SERIAL, PKI_CA_NAME_BLACKLIST
    from hashlib import md5 as md5_constructor
    from md5 import new as md5_constructor

        
        x509_list =[]
        for x509 in pki.models.x509Extension.objects.all():
            if x509.is_ca():
                x509.ca = True
            else:
                x509.ca = False
            x509_list.append(x509)
        
        # render template and save result to openssl.conf
        conf = render_to_string(PKI_OPENSSL_TEMPLATE, {'ca_list': ca_list, 'x509_extensions': x509_list,})
        
        f = open(PKI_OPENSSL_CONF, 'wb')
        f.write(conf)
        f.close()
    except Exception, e:
        logger.exception("Refreshing PKI metadata failed: %s" % e)
    
    logger.info("Successfully finished PKI metadata refresh")

class Openssl():
    """OpenSSL command and task wrapper class
    
    instance must be a CertificateAuthority or Certificate object.
    """
    
    def __init__(self, instance):
        """Initialize shared varaibles and verify instance type"""
        
        self.i    = instance

        self.subj = subject_for_object(self.i)