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

# Copyright 2008-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.

from __future__ import absolute_import
import sys
import os
import hashlib
import crypt
import string
from random import choice
from base64 import encodestring as _b64enc

b64encode = lambda x: _b64enc(x).rstrip()
try:
    from smbpasswd import lmhash, nthash
except ImportError:
    lmhash, nthash = None, None
from .cl_print import color_print
from . import cl_overriding
from calculate.contrib.passlib.hash import sha256_crypt, grub_pbkdf2_sha512

from calculate.lib.cl_lang import setLocalTranslate

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

def get_shadow_hash():
    """
    Получить энкриптор для паролей unix
    :return:
    """
    return sha256_crypt.using(rounds=5000, salt_size=8)

def get_grub_hash():
    """
    Получить энкриптор для паролей grub
    :return:
    """
    return grub_pbkdf2_sha512

class encrypt(color_print):
    """Класс хранения общих методов используемых для настройки сервисов

    Методы шифрования, создания сертификатов и.т. д
    """

    def __GenCryptSalt__(self, len=2):
        """Генерация соли для хеширования пароля (CRYPT)"""
        chars = string.letters + string.digits + "./"
        salt = ""
        for i in range(len):
            salt = salt + choice(chars)
        return salt

    def getHashPasswd(self, password, SecHashAlg):
        """Генерация хеша пароля,

        Поддерживаемые алгоритмы шифрования пароля:
        plain, md5, smd5, crypt, sha, ssha, lm, nt, shadow_ssha512,
        shadow_ssha256, shadow_md5
        """
        if not password:
            self.printERROR(_("ERROR") + " getHashPasswd: " +
                            _("empty password"))
            return False

        if SecHashAlg == "plain":
            hash_pwd = password

        elif SecHashAlg == "md5":
            h = hashlib.md5(password)
            hash_pwd = "{MD5}" + b64encode(h.digest())

        elif SecHashAlg == "smd5":
            salt = os.urandom(4)
            h = hashlib.md5(password)
            h.update(salt)
            hash_pwd = "{SMD5}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "shadow_ssha512":
            salt = self.__GenCryptSalt__(8)
            hash_pwd = crypt.crypt(password, "$6$%s$" % salt)

        elif SecHashAlg == "shadow_ssha256":
            salt = self.__GenCryptSalt__(8)
            hash_pwd = crypt.crypt(password, "$5$%s$" % salt)

        elif SecHashAlg == "shadow_md5":
            salt = self.__GenCryptSalt__(8)
            hash_pwd = crypt.crypt(password, "$1$%s$" % salt)

        elif SecHashAlg == "crypt":
            salt = self.__GenCryptSalt__()
            hash_pwd = "{CRYPT}" + crypt.crypt(password, salt)

        elif SecHashAlg == "sha":
            h = hashlib.sha1(password)
            hash_pwd = "{SHA}" + b64encode(h.digest())

        elif SecHashAlg == "ssha":
            salt = os.urandom(4)
            h = hashlib.sha1(password)
            h.update(salt)
            hash_pwd = "{SSHA}" + b64encode(h.digest() + salt)

        elif SecHashAlg == "lm" and lmhash:
            hash_pwd = lmhash(password)
        elif SecHashAlg == "nt" and nthash:
            hash_pwd = nthash(password)
        else:
            if SecHashAlg in ("lm", "nt"):
                self.printERROR(
                    _("ERROR") + " getHashPasswd: " +
                    (_("Failed to support '%s' encryption algorithm")
                     % SecHashAlg) + " " + _("without py-smbpasswd"))
            else:
                self.printERROR(_("ERROR") + " getHashPasswd: " +
                                _("Failed to support '%s' encryption algorithm")
                                % SecHashAlg)
            return False
        return hash_pwd


def getHash(password, encr):
    """Получить хеш пароля

    password - пароль
    encr - алгоритм шифрования, например 'ssha'
    """
    encryptObj = encrypt()
    hashPwd = encryptObj.getHashPasswd(password, encr.lower())
    if hashPwd:
        return hashPwd
    else:
        encryptObj.printERROR(_("Password encryption error, "
                                "method getHash()"))
        cl_overriding.exit(1)
