#!python3

import hashlib
import os
import getpass
from bash import bash

base58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
passwd_len = 16


def sha_n_times(msg, n):
    msg = str.encode(msg)
    for _ in range(n):
        msg = hashlib.sha256(msg).digest()
    return msg


def if_no_number_add_one(passwd):
    if not set(passwd) & set("123456789"):
        passwd = passwd[:-2] + "1" + passwd[-1:]
    return passwd


def if_no_capital_add_one(passwd):
    if not set(passwd) & set("ABCDEFGHJKLMNPQRSTUVWXYZ"):
        passwd = passwd[:-3] + "A" + passwd[-2:]
    return passwd


def if_no_lower_add_one(passwd):
    if not set(passwd) & set("abcdefghijkmnopqrstuvwxyz"):
        passwd = passwd[:-4] + "a" + passwd[-3:]
    return passwd


def bytes_to_base58(msg):
    b58_msg = ""
    for char in msg:
        b58_msg += base58[char % 58]
    return b58_msg


def clear_n_last_lines(n):
    os.system(f"tput cuu {n}")


def print_blanc(n):
    print('\n' * n)


def print_header():
    print(
        r"""
__________  _____    _________ _________ ___________________ _______   
\______   \/  _  \  /   _____//   _____//  _____/\_   _____/ \      \  
 |     ___/  /_\  \ \_____  \ \_____  \/   \  ___ |    __)_  /   |   \ 
 |    |  /    |    \/        \/        \    \_\  \|        \/    |    \
 |____|  \____|__  /_______  /_______  /\______  /_______  /\____|__  /
                 \/        \/        \/        \/        \/         \/ 
        """
    )
    print('\n'*4)
    clear_n_last_lines(2)


def echo(msg):
    os.system(f'echo "{msg}"')


def remove_header():
    clear_n_last_lines(12)


if __name__ == "__main__":
    try:
        print_header()
        master_key = getpass.getpass(prompt="type in MASTER key\n")
        clear_n_last_lines(5)
        print_blanc(2)

        while True:
            domain = getpass.getpass(prompt="type in DOMAIN name\n")
            clear_n_last_lines(4)
            hash_b58 = bytes_to_base58(sha_n_times(domain + master_key, 10 ** 5))
            passwd = hash_b58[:passwd_len]
            passwd = if_no_number_add_one(passwd)
            passwd = if_no_capital_add_one(passwd)
            passwd = if_no_lower_add_one(passwd)
            bash(f"echo '!{passwd}!' | xsel -i -b")
            passwd = None
            echo("PASSWORD IS NOW IN YOUR CLIPBOARD\n")

    except (KeyboardInterrupt, EOFError):
        remove_header()
