#! /usr/bin/env python

import os
import sys

from getpass import getpass
from getopt import getopt, GetoptError
from kdb_file import KdbReader, KdbReaderFileParseError, KdbReaderDecodeFailError

def usage():
    return """A light-weight commandline interface to KeePassX database-files.

-f, --file      the database file to open
-h, --help      this right here

-p, --password  don't use this

Source at http://github.com/bjornars/PyKeePass """

def error(text):
    print >>sys.stderr, text
    sys.exit(-1)

def get_clean(method, *args):
    try:
        return method(*args)
    except KeyboardInterrupt:
        sys.exit(-1)

def get_password():
    while 1:
        password = get_clean(getpass)
        if not password:
            error('blank password')
        try:
            kr.parse(password)
            break
        except KdbReaderDecodeFailError:
            print >>sys.stderr, "error decoding, wrong passsword?"

try:
    opts, rest = getopt(sys.argv[1:], "f:p:h", ["file=", "password=", "help"])
    if rest: raise GetoptError("a tad too many arguments")
except GetoptError as e:
    print >> sys.stderr, e
    sys.exit(-1)

opts = dict(opts)
if '-h' in opts or '--help' in opts:
    print usage()
    sys.exit(0)

filename = opts.get('-f') or opts.get('--file') or get_clean(raw_input, 'Password file: ')
full_filename = os.path.expanduser(filename)
if not os.path.isfile(full_filename):
    error( "Cannot find/open %s" % filename)

# read file
kr = KdbReader(full_filename)

#decode with password
password = opts.get('-p') or opts.get('--password')
if password:
    kr.parse(password)
else:
    get_password()

print "File read and decoded successfully"
while 1:
    try:
        term = get_clean(raw_input, 'Search term (or blank): ')

        if term:
            print kr.search(term)
        else:
            print kr.list()
        get_clean(raw_input,'Done? ')

    except EOFError:
        break
    finally:
        # clear screen
        print '\033[2J'


