#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2012-2013 Karsten-Kai König <kkoenig@posteo.de>

This file is part of keepassc.

keepassc is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or at your
option) any later version.

keepassc is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with keepassc.  If not, see <http://www.gnu.org/licenses/>.
'''

import argparse
from curses import wrapper
from getpass import getpass
from os import geteuid
from os.path import expanduser, realpath, splitext
from sys import exit, stdout

from keepassc.control import Control
from kppy import KPDB, KPError


__doc__ = '''This program gives you access to your KeePass 1.x or
          KeePassX databases through a nice curses interface.

          It is completely controllable with the keyboard.

         '''


def arg_parse():
    "Parse the command line arguments"
    parser = argparse.ArgumentParser()
    parser.add_argument('--asroot', action='store_true', default=False,
                        help='parse option to execute keepassc as root user')
    parser.add_argument('-d', '--database', default=None,
                        help='Path to database file.')
    parser.add_argument('-k', '--keyfile', default=None,
                        help='Path to keyfile.')
    parser.add_argument('-e', '--entry', help='Print entry with parsed '
                        'title\nYou will see a password prompt; leave it '
                        'blank if you only want to use a key-file\nJust '
                        'type a part of the entry title lower-case, '
                        'it\'s case-insensitive and will search for '
                        'matching string parts\n\n'
                        'WARNING: Your passwords will be displayed '
                        'directly on your command line!')
    return parser.parse_args()


def parse_entry(entry, database, password, keyfile):
    """Given the --entry command line option, parse the database and
    return a matching entry.

    Args:
        entry:      the search string
        database:   path to the database file
        password:   password result from getpass()
        keyfile:    path to the keyfile

    """
    try:
        db = KPDB(database, password, keyfile)
    except KPError as err:
        print(err)
        exit()
    for i in db._entries:
        if entry.lower() in i.title.lower():
            print('Title: ' + i.title)
            if i.url is not None:
                stdout.write('URL: ' + i.url + '\n')
            if i.username is not None:
                stdout.write('Username: ' + i.username + '\n')
            if i.password is not None:
                stdout.write('Password: ' + i.password + '\n')
            if i.creation is not None:
                stdout.write('Creation: ' + i.creation.__str__() + '\n')
            if i.last_access is not None:
                stdout.write('Access: ' + i.last_access.__str__() + '\n')
            if i.last_mod is not None:
                stdout.write('Modification: ' + i.last_mod.__str__() + '\n')
            if i.expire is not None:
                stdout.write('Expiration: ' + i.expire.__str__() + '\n')
            if i.comment is not None:
                stdout.write('Comment: ' + i.comment + '\n\n')
            stdout.flush()

if __name__ == '__main__':
    args = arg_parse()
    if geteuid() == 0 and args.asroot is False:
        print('If you really want to execute this program as root user type '
              '\'keepassc --asroot\'')
        print('Warning: This will annul a security concept of keepassc')
    else:
        if args.entry:
            password = getpass()
            if password == '':
                password = None
            parse_entry(args.entry, args.database, password, args.keyfile)
        elif args.database and splitext(args.database)[-1] == '.kdb':
            filepath = realpath(expanduser(args.database))
            app = Control()
            wrapper(app.main_loop(filepath))
        else:
            app = Control()
            wrapper(app.main_loop())
