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

# Copyright 2012-2016 Mir Calculate. 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.lib.datavars import DataVars
from calculate.lib.cl_lang import setLocalTranslate

_ = lambda x: x
setLocalTranslate('cl_console3', sys.modules[__name__])


def passphrase_callback(v):
    if type(v) == int or not v:
        return ""
    return str(v)


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 = input(_("Enter the certificate data 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 = DataVars()
    clVars.flIniFile()
    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()
        _CN = input(_('Host Name [%s]: ') % result_host_name)
        name.CN = _CN or result_host_name

        _OU = input(_('User Name [%s]: ') % username)
        name.OU = _OU or username
        _O = input(_('Organization Name: '))
        name.O = _O or ""

        _L = input(_('Network address (hostname or IP) [%s]: ')
                           % host_name)
        name.L = _L or ""
        _ST = input(_('City: '))
        name.ST = _ST or ""
        _C = input(_('Country (2 characters): [%s]') % lang)
        name.C = _C or lang

    else:
        name.CN = result_host_name or ""  # Имя сертификата (Common Name);
        name.OU = username or ""  # Название отдела (Organization Unit);
        name.O = 'My Company'  # Название организации (Organization Name);
        name.L = host_name or ""  # Название города (Locality Name);
        name.ST = 'My State'  # Название региона (State Name);
        name.C = lang or "C"  # Двухсимвольный код страны (Country);
    req.set_subject_name(name)

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