#-*- coding: utf-8 -*-

# Copyright 2012 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  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.

import os, re
import threading, hashlib
import datetime
import OpenSSL

def add_cert(mac, client_type, data_path, client_certbase):
    curThread = threading.currentThread()
    try:
        ip = curThread.REMOTE_ADDR
    except:
        print "EXCEPT ip = curThread.REMOTE_ADDR!"

    cert = curThread.client_cert

    # Finding Id for the current certificate
    ID_FILE = data_path + '/client_certs/id.int'

    if os.path.exists(ID_FILE):
        fi = open(ID_FILE, 'r')
        temp = fi.read()
        fi.close()
        i = int(temp)
    else:
        count = 0
        with open(client_certbase) as fd:
            t = fd.read()
            # See each line
            for line in t.splitlines():
                count += 1

        count += 1
        fi = open(ID_FILE, 'w')
        fi.write(str(count))
        fi.close()
        i = count

    CERT_FILE = data_path + '/client_certs/' + str(i) + '.crt'
    fc = open(CERT_FILE, 'w')
    fc.write(cert)
    fc.close()

    md5 = hashlib.md5()
    md5.update(cert)
    md5sum = md5.hexdigest()
    date = datetime.datetime.now()

    line = ("%s %s %s %s %s %s\n" %(i, md5sum, date, ip, mac, client_type))
    fd = open(client_certbase, 'a')
    fd.write(line)
    fd.close()

    i += 1
    fi = open(ID_FILE, 'w')
    temp = str(i)
    fi.write(temp)
    fi.close()
    return str(i-1)

def get_ca(cert_path):
    server_cert = open (cert_path + '/server.crt','r').read()
    ca_certs = open (cert_path + '/ca_root.crt','r').read()

    certobj = OpenSSL.crypto.load_certificate \
                    (OpenSSL.SSL.FILETYPE_PEM, server_cert)

    Issuer = certobj.get_issuer().get_components()
    for item in Issuer:
        if item[0] == 'CN':
            issuer_CN = item[1]

    if not 'issuer_CN' in locals():
        return '1'

    p = re.compile('[-]+[\w ]+[-]+\n+[\w\n\+\\=/]+[-]+[\w ]+[-]+\n?')
    ca_certs_list = p.findall(ca_certs)
    for ca in ca_certs_list:
        certobj = OpenSSL.crypto.load_certificate \
                            (OpenSSL.SSL.FILETYPE_PEM, ca)

        Subject = certobj.get_subject().get_components()
        for subj in Subject:
            if subj[0] == 'CN' and subj[1] == issuer_CN:
                return ca
    return '2'
    