#!/usr/bin/env python
# encoding:utf8
"""Read and copy Keepass database entries using dmenu or rofi

"""
from datetime import datetime, timedelta
from io import BytesIO
import itertools
import locale
import os
from os.path import expanduser
import shlex
import sys
from subprocess import Popen, PIPE
import gpgme
from pykeepass import PyKeePass
from pykeyboard import PyKeyboard

try:
    import cPickle as pickle
except ImportError:
    import pickle
try:
    import configparser as configparser
except ImportError:
    import ConfigParser as configparser

ENV = os.environ.copy()
ENV['LC_ALL'] = 'C'
ENC = locale.getpreferredencoding()
CACHE_FILE = expanduser("~/.cache/keepmenu")
CACHE_EXPIRY_FILE = expanduser("~/.cache/keepmenu_exp")
CACHE_PERIOD_DEFAULT = 6
CONF_FILE = expanduser("~/.config/keepmenu/config.ini")
CONF = configparser.ConfigParser()
CONF.read(CONF_FILE)
if CONF.has_option("database", "pw_cache_period"):
    CACHE_PERIOD = int(CONF.get("database", "pw_cache_period"))
else:
    CACHE_PERIOD = CACHE_PERIOD_DEFAULT
GPG = gpgme.Context()

if sys.version_info.major < 3:
    str = unicode


def dmenu_cmd(num_lines, prompt="Entries"):  # pylint: disable=too-many-branches
    """Parse config.ini for dmenu options

    Args: args - num_lines: number of lines to display
                 promp: prompt to show
    Returns: command invocation (as a list of strings) for
                dmenu -l <num_lines> -p <prompt> -i ...

    """
    dmenu_command = "dmenu"
    if not CONF.has_section('dmenu'):
        dmenu = [dmenu_command, "-i", "-l", str(num_lines), "-p", str(prompt)]
    else:
        args = CONF.items('dmenu')
        args_dict = dict(args)
        dmenu_args = []
        if "dmenu_command" in args_dict:
            command = shlex.split(args_dict["dmenu_command"])
            dmenu_command = command[0]
            dmenu_args = command[1:]
            del args_dict["dmenu_command"]
        if "rofi" in dmenu_command:
            lines = "-i -dmenu -lines"
            # rofi doesn't support 0 length line, it requires at least -lines=1
            # see https://github.com/DaveDavenport/rofi/issues/252
            num_lines = num_lines or 1
        else:
            lines = "-i -l"
        if "l" in args_dict:
            # rofi doesn't support 0 length line, it requires at least -lines=1
            # see https://github.com/DaveDavenport/rofi/issues/252
            if "rofi" in dmenu_command:
                args_dict['l'] = min(num_lines, int(args_dict['l'])) or 1
            lines = "{} {}".format(lines, args_dict['l'])
            del args_dict['l']
        else:
            lines = "{} {}".format(lines, num_lines)
        if "pinentry" in args_dict:
            del args_dict["pinentry"]
    if prompt == "Passphrase":
        if CONF.has_section('dmenu_passphrase'):
            args = CONF.items('dmenu_passphrase')
            args_dict.update(args)
        rofi_obscure = True
        if CONF.has_option('dmenu_passphrase', 'rofi_obscure'):
            rofi_obscure = CONF.getboolean('dmenu_passphrase', 'rofi_obscure')
            del args_dict["rofi_obscure"]
        if rofi_obscure is True and "rofi" in dmenu_command:
            dmenu_args.extend(["-password"])
    extras = (["-" + str(k), str(v)] for (k, v) in args_dict.items())
    dmenu = [dmenu_command, "-p", str(prompt)]
    dmenu.extend(dmenu_args)
    dmenu += list(itertools.chain.from_iterable(extras))
    dmenu[1:1] = lines.split()
    dmenu = list(filter(None, dmenu))  # Remove empty list elements
    return dmenu


def dmenu_err(prompt):
    """Pops up a dmenu prompt with an error message

    """
    Popen(dmenu_cmd(1, prompt), stdin=PIPE, stdout=PIPE,
          env=ENV).communicate(input='')
    return


def get_databases():
    """Return all available databases from config.ini

    Returns: [(database name, keyfile, passphrase), (database2, kf, pw), ...]
    """
    if not CONF.has_section('database'):
        dmenu_err("No databases defined in {}".format(CONF_FILE))
        sys.exit()
    args = CONF.items('database')
    args_dict = dict(args)
    dbs = []
    idx = 1
    while True:
        try:
            dbn = expanduser(args_dict['database_{}'.format(idx)])
        except KeyError:
            break
        try:
            keyfile = expanduser(args_dict['keyfile_{}'.format(idx)])
        except KeyError:
            keyfile = ''
        try:
            passw = args_dict['password_{}'.format(idx)]
        except KeyError:
            passw = ''
        dbs.append((dbn, keyfile, passw))
        idx += 1
    return dbs


def open_database(dbo):
    """Open keepass database and return the PyKeePass object

        Args: dbo: tuple (db path, keyfile path, password)
        Returns: PyKeePass object

    """
    dbf, keyfile, password = dbo
    if not password:
        password = get_passphrase()
        if CONF.has_option("database", "gpg_key"):
            cache_passphrase(password)
    try:
        kpo = PyKeePass(dbf, password, keyfile=keyfile)
    except IOError:
        dmenu_err("Database does not exists")
        sys.exit()
    except OSError:
        dmenu_err("Invalid Password or keyfile")
        sys.exit()
    return kpo


def get_cached_passphrase():
    """Retrieve cached passphrase if possible

    """
    # First check if the cache file exists and if it is expired
    try:
        with open(CACHE_EXPIRY_FILE, 'rb') as cef:
            expiry = pickle.load(cef)
    except IOError:
        return ""
    if datetime.now() > expiry:
        return ""
    with BytesIO() as data:
        try:
            with open(CACHE_FILE, 'rb') as cache:
                GPG.decrypt(cache, data)
                password = data.getvalue().decode(ENC).rstrip('\n')
        except IOError:
            return ""
        except gpgme.GpgmeError:
            return ""
    return password


def cache_passphrase(password):
    """Save passphrase to cache file

    """
    key = CONF.get("database", "gpg_key")
    gpg_key = GPG.get_key(key)
    with BytesIO(password.encode(ENC)) as data:
        try:
            with open(CACHE_FILE, 'wb') as cache:
                GPG.encrypt([gpg_key], 0, data, cache)
        except gpgme.GpgmeError:
            dmenu_err("Gpg error...unable to cache passphrase")
    with open(CACHE_EXPIRY_FILE, 'wb') as cef:
        pickle.dump(datetime.now() + timedelta(hours=CACHE_PERIOD), cef, -1)


def get_passphrase():
    """Get a database password from dmenu, pinentry or cached gpg encrypted file

    Returns: string

    """
    pinentry = None
    if CONF.has_option("database", "gpg_key"):
        password = get_cached_passphrase()
    if password:
        return password
    if CONF.has_option("dmenu", "pinentry"):
        pinentry = CONF.get("dmenu", "pinentry")
    if pinentry:
        password = ""
        out = Popen(pinentry,
                    stdout=PIPE,
                    stdin=PIPE).communicate( \
                            input=b'setdesc Enter database password\ngetpin\n')[0]
        if out:
            res = out.decode(ENC).split("\n")[2]
            if res.startswith("D "):
                password = res.split("D ")[1]
    else:
        password = Popen(dmenu_cmd(0, "Passphrase"),
                         stdin=PIPE,
                         stdout=PIPE).communicate()[0].decode(ENC).rstrip('\n')
    return password


def type_entry(entry):
    """Use PyUserInput to type the selected entry

    """
    kbd = PyKeyboard()
    if entry.username:
        kbd.type_string(entry.username)
        if entry.password:
            kbd.tap_key(kbd.tab_key)
    if entry.password:
        kbd.type_string(entry.password)
    # Not sure why we need n=2, but only seems to work that way
    kbd.tap_key(kbd.enter_key, n=2)


def run():
    """Main script entrypoint"""
    databases = get_databases()
    if len(databases) == 1:
        keepass = open_database(databases[0])
    else:
        inp_bytes = "\n".join(i[0] for i in databases).encode(ENC)
        sel = Popen(dmenu_cmd(len(databases)), stdin=PIPE, stdout=PIPE,
                    env=ENV).communicate(input=inp_bytes)[0].decode(ENC)
        if not sel.rstrip():
            sys.exit()
        keepass = open_database([i for i in databases if i[0] == sel.strip()][0])
    entries = keepass.entries
    num_align = len(str(len(entries)))
    entry_pattern = "{:>{na}} - {} - {} - {}"  # Path,username,url
    # Have to number each entry to capture duplicates correctly
    entries_b = "\n".join([entry_pattern.format(j, i.path, i.username, i.url, na=num_align)
                           for j, i in enumerate(entries)]).encode(ENC)
    sel = Popen(dmenu_cmd(min(24, len(entries))), stdin=PIPE, stdout=PIPE,
                env=ENV).communicate(input=entries_b)[0].decode(ENC)
    if not sel.rstrip():
        sys.exit()
    entry = entries[int(sel.split('-', 1)[0])]
    type_entry(entry)


if __name__ == '__main__':
    run()

# vim: set et ts=4 sw=4 :
