#!/usr/bin/env python
#============================================================================
# This file is part of Pwman3.
#
# Pwman3 is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2
# as published by the Free Software Foundation;
#
# Pwman3 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 Pwman3; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#============================================================================
# Copyright (C) 2012 Oz Nahum <nahumoz@gmail.com>
#============================================================================
# Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
#============================================================================
import os
import os.path
import subprocess as sp

_saveconfig = True

import argparse


parser = argparse.ArgumentParser(description='pwman3 - a command line password'\
+'manager.')
parser.add_argument('-c','--config', dest='cfile',
                    default=os.path.expanduser("~/.pwman/config"),
                    help='cofiguretion file to read')
parser.add_argument('-d', '--database', dest='dbase',
                    default=os.path.expanduser("~/.pwman/pwman.db"))

parser.add_argument('-e', '--encryption', dest="algo", default="Blowfish",
                help="Possible options are: AES, ARC2, ARC4, "\
                +"Blowfish(default) CAST, DES, DES3, IDEA, RC5")

parser.add_argument('-t','--test',  help="Run pwman from current directory \
without installation", action="store_true")
args = parser.parse_args()

if args.test:
    import sys
    sys.path.insert(0,os.getcwd())

from pwman.util.crypto import CryptoEngine
import getopt
import sys

if 'darwin' in sys.platform:
    from pwman.ui.cli import PwmanCliMac as PwmanCli
    OSX = True
else:
    from pwman.ui.cli import PwmanCli
    OSX = False


import pwman.util.config as config
import pwman.data.factory

config_file=args.cfile



def which(cmd):
    _, cmdname = os.path.split(cmd)

    for path in os.environ["PATH"].split(os.pathsep):
        cmd = os.path.join(path, cmdname)
        if os.path.isfile(cmd) and os.access(cmd, os.X_OK):
            return cmd

    return None

try:
    config_dir = os.path.expanduser("~/.pwman")
    if not os.path.isdir(config_dir):
        os.mkdir(config_dir)

    config_file = os.path.join(config_dir, "config")
    # set cls_timout to negative number (e.g. -1) to disable
    default_config = {'Global': {'umask': '0100', 'colors': 'yes',
                                 'cls_timeout': '5'
                                },
                      'Database': {'type': 'SQLite',
                                   'filename': os.path.join(config_dir,
                                                            "pwman.db")},
                      'Encryption': {'algorithm': 'Blowfish'},
                      'Readline': {'history': os.path.join(config_dir,
                                                           "history")}
                      }
    
    config.set_defaults(default_config)
    
    if os.path.exists(config_file):
        config.load(config_file)
        xselpath = config.get_value("Global", "xselpath")
    elif not OSX :
        xselpath = which("xsel")
        config.set_value("Global", "xsel", xselpath)
    elif OSX:
        pbcopypath = which("pbcopy")
        config.set_value("Global", "xsel", pbcopypath)

    if args.dbase !=  config.get_value('Database', "filename"):
        config.set_value("Database", "filename", args.dbase)
        _saveconfig = False
    if args.algo != "Blowfish":
            config.set_value("Encryption", "algorithm", args.algo)
            _saveconfig = False

    # set umask before creating/opening any files
    umask = int(config.get_value("Global", "umask"))
    os.umask(umask)

    enc = CryptoEngine.get()
    
    dbtype = config.get_value("Database", "type")
    db = pwman.data.factory.create(dbtype)
    cli = PwmanCli(db, xselpath)
except SystemExit, e:
    sys.exit(e)
except Exception, e:
    print "Error: %s" % (e)
    sys.exit(-1)

try:
    try:
        cli.cmdloop()
    except KeyboardInterrupt, e:
        print e
finally:
    try:
        if _saveconfig:
            config.save(config_file)
    except Exception, e:
        print "Error: %s" % (e)
        sys.exit(-1)
