#!/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>
#============================================================================
from __future__ import print_function
import os
import sys
import re
import shutil
from pwman import default_config, which
from pwman import parser_options
from pwman.ui import get_ui_platform
from pwman.ui.tools import CLICallback
import pwman.util.config as config
import pwman.data.factory
from pwman.data.convertdb import PwmanConvertDB
from pwman.util.crypto import CryptoEngine

_db_warn = ("pwman3 detected that you are using the old database format"
            " which is insecure."
            " pwman3 will try to automatically convert the database now."
            "\n"
            "If you choose not to convert the database, pwman3, will quit."
            "\nYou can check the help (pwman3 -h) or look at the manpage how to convert "
            " the database manually."
            )


def get_conf(args):
    config_dir = os.path.expanduser("~/.pwman")

    if not os.path.isdir(config_dir):
        os.mkdir(config_dir)

    if not os.path.exists(args.cfile):
        config.set_defaults(default_config)
    else:
        config.load(args.cfile)

    return config


def set_xsel(config, OSX):
    if not OSX:
        xselpath = which("xsel")
        config.set_value("Global", "xsel", xselpath)
    elif OSX:
        pbcopypath = which("pbcopy")
        config.set_value("Global", "xsel", pbcopypath)


def set_win_colors(config):
    if 'win' in sys.platform:
        try:
            import colorama
            colorama.init()
        except ImportError:
            config.set_value("Global", "colors", 'no')


def set_umask(config):
    # set umask before creating/opening any files
    try:
        umask = config.get_value("Global", "umask")
        if re.search(r'^\d{4}$', umask):
            os.umask(int(umask))
        else:
            raise ValueError
    except ValueError:
        print("Could not determine umask from config!")
        sys.exit(2)


def set_db(args):
    if args.dbase:
        config.set_value("Database", "filename", args.dbase)
        config.set_value("Global", "save", "False")


def set_algorithm(args, config):
    if args.algo:
        config.set_value("Encryption", "algorithm", args.algo)
        config.set_value("Global", "save", "False")

def get_conf_options(args, OSX):

    config = get_conf(args)
    xselpath = config.get_value("Global", "xsel")
    if not xselpath:
        set_xsel(config, OSX)

    set_win_colors(config)
    set_db(args)
    set_umask(config)
    set_algorithm(args, config)
    dbtype = config.get_value("Database", "type")
    if not dbtype:
        print("Could not read the Database type from the config!")
        sys.exit(1)

    return xselpath, dbtype


def get_db_version(config, dbtype, args):
    if os.path.exists(config.get_value("Database", "filename")):
        dbver = pwman.data.factory.check_db_version(dbtype)
        if dbver < 0.4 and not args.dbconvert:
            print(_db_warn)
    else:
        dbver = 0.4
    return dbver


def auto_convert():
    try:
        #1) Display a message saying that the database will be converted
        # This step is done already in get_db_version
        dbconvertor = PwmanConvertDB(args, config)

        #2) copy the old database : cp ~/.pwman3/pwman.db ~/.pwman3/pwman.backup-2013-11-23-23:15.db
        #3) Display a message about the backup file path
        # These steps are done by PwmanConvertDB.backup_old_db()
        dbconvertor.backup_old_db()

        #4) convert the old database to the new format in ~/.pwman3/pwman.db
        # This step is done by PwmanConvertDB.create_new_db()
        #                      PwmanConvertDB.convert_nodes()
        #                      PwmanConvertDB.save_new_nodes_to_db()
        #                      PwmanConvertDB.save_old_key()
        dbconvertor.read_old_db()
        dbconvertor.create_new_db()
        dbconvertor.convert_nodes()
        dbconvertor.save_new_nodes_to_db()
        dbconvertor.save_old_key()
        #5) Display a message about the result of the conversion
        # add message here ...
        #5b) close connection
        dbconvertor.db.close()
        print("Your datbase %s was successfully converted " % dbconvertor.dbname)
        #5c) rename the newly created db to the old name!
        shutil.move(dbconvertor.newdb_name, dbconvertor.dbname)
        #6) Start the pwman3 normally if all went ok
        return True
    except Exception, e:
        raise e


def main(args):
    PwmanCliNew, OSX = get_ui_platform(sys.platform)
    xselpath, dbtype = get_conf_options(args, OSX)
    enc = CryptoEngine.get()
    dbver = get_db_version(config, dbtype, args)

    if args.dbconvert:
        dbconvertor = PwmanConvertDB(args, config)
        dbconvertor.run()
        sys.exit(0)

    if dbver < 0.4:
        ans = raw_input("Would you like to proceed with the conversion of the database"
                        " before starting pwman3 [y/N]?")
        if ans.lower() != "y":
            sys.exit(1)

        auto_convert()
        dbver = 0.4

    db = pwman.data.factory.create(dbtype, dbver)
    cli = PwmanCliNew(db, xselpath, CLICallback)

    try:
        cli.cmdloop()
    except KeyboardInterrupt, e:
        print(e)

    if config.get_value("Global", "save") == "True":
        try:
            config.save(args.cfile)
        except Exception, e:
            print ("Error: %s" % e)
            sys.exit(-1)

if __name__ == '__main__':
    args = parser_options().parse_args()
    main(args)
