# -*- 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 sys
import socket
from M2Crypto import RSA, X509, EVP, m2
from calculate.core.datavars import DataVarsCore

_ = lambda x: x
from calculate.lib.cl_lang import setLocalTranslate

setLocalTranslate('cl_core3', sys.modules[__name__])


def passphrase_callback(v):
    return None


def generateRSAKey():
    return RSA.gen_key(2048, m2.RSA_F4)


def makePKey(key):
    pkey = EVP.PKey()
    pkey.assign_rsa(key)
    return pkey


def makeRequest(pubkey, pkey, serv_host, auto=False):
    """ create query to the signing on server """
    req = X509.Request()
    # Seems to default to 0, but we can now set it as well, so just API test
    req.set_version(req.get_version())
    req.set_pubkey(pkey)
    name = X509.X509_Name()
    if auto:
        c = 'n'
    else:
        c = raw_input(_("Enter the certificate date manually? y/[n]: "))
    # Get HostName
    host_name = socket.getfqdn()
    list_host_name = host_name.split('.')
    result_host_name = list_host_name[0] + "@" + serv_host
    # Get username
    clVars = DataVarsCore()
    if not clVars.flIniFile():
        sys.exit(1)
    username = clVars.Get('ur_fullname')
    # Get language
    lang = clVars.Get('os_locale_locale')[:2]

    if c.lower() in ['y', 'yes']:
        # if serv_host in host_name:
        # host_name = host_name.replace('.'+serv_host, '')
        # list_host_name = host_name.split('.')
        # result_host_name =  \
        # list_host_name[len(list_host_name)-1]+"@"+serv_host
        # else:
        # host_name = socket.getfqdn()
        name.CN = raw_input(_('Hostname [%s] : ') % result_host_name)
        if name.CN in ['', None]:
            name.CN = result_host_name

        name.OU = raw_input(_('Username [%s]: ') % username)
        if name.OU in ['', None]:
            name.OU = username
        name.O = raw_input(_('Organization name: '))
        name.L = raw_input(_('Network address (hostname or IP) [%s]: ')
                           % host_name)
        name.ST = raw_input(_('City: '))
        name.C = raw_input(_('Country: [%s]') % lang)
        if not name.C:
            name.C = lang
    else:
        name.CN = result_host_name  # Имя сертификата (Common Name);
        name.OU = username  # Название отдела (Organization Unit);
        name.O = 'My Company'  # Название организации (Organization Name);
        name.L = host_name  # Название города (Locality Name);
        name.ST = 'My State'  # Название региона (State Name);
        name.C = lang  # Двухсимвольный код страны (Country);
    req.set_subject_name(name)

    ext1 = X509.new_extension('Comment', 'Auto Generated')
    extstack = X509.X509_Extension_Stack()
    extstack.push(ext1)
    req.add_extensions(extstack)
    req.sign(pkey, 'md5')
    return req
