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

# Copyright 2012-2015 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 re
import threading
import hashlib
import datetime
from calculate.lib.utils.files import readFile, readLinesFile


def add_cert(mac, client_type, client_counter, client_certname,
             client_certbase):
    cur_thread = threading.currentThread()
    try:
        ip = cur_thread.REMOTE_ADDR
    except AttributeError:
        ip = "localhost"

    cert = cur_thread.client_cert

    # получить идентификатор из файла-счетчика или посчитать количество строк
    try:
        i = int(readFile(client_counter))
    except ValueError:
        i = len(list(readLinesFile(client_certbase))) + 1

    with open(client_certname, 'w') as f:
        f.write(cert)

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

    with open(client_certbase, 'a') as f:
        f.write("%s %s %s %s %s %s\n" % (i, md5sum, date, ip, mac, client_type))

    with open(client_counter, 'w') as f:
        f.write(str(i + 1))
    return str(i)


def get_ca(cert_path):
    import OpenSSL

    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()
    issuer_CN = None
    for item in Issuer:
        if item[0] == 'CN':
            issuer_CN = item[1]

    if issuer_CN is None:
        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'
