# -*- coding: utf-8 -*-

""" Odoo databases management script """

import argparse
import common
import odoorpc


def str2bool(val):
    """ Convert sense str to boolean """
    return val.lower() in ('yes', 'true', '1')

def dump(odoo, args):
    """ Backup database on path """
    dump_path = u'{}/{}_{}.zip'.format(args.dump_path, args.host, args.database)
    dump_file = odoo.db.dump(args.password, args.database)
    with open(dump_path, 'wb') as dump_zip:
        dump_zip.write(dump_file.read())

def restore(odoo, args):
    """ Restores database from local file to local or remote host """
    if args.dump_full_path:
        dump_path = args.dump_full_path
    else:
        dump_path = u'{}/{}_{}.zip'.format(args.dump_path, args.host, args.database)
    with open(dump_path, 'rb') as dump_file:
        if args.target_host and args.target_port and args.target_password:
            connection = odoorpc.ODOO(args.target_host, port=args.target_port)
            connection.config['timeout'] = 600
            password = args.target_password
        else:
            connection = odoo
            password = args.password
        connection.db.restore(password, args.database_target or args.database,
                              dump_file, args.restore_copy)

def main():
    """ Main function with argument parsing """
    parser = argparse.ArgumentParser(description='Odoo database creation '
                                     'according to their names')
    parser = common.parser(parser)
    parser.add_argument('-a', '--action', type=str, required=True,
                        help=('action for the database : create, drop, '
                              'duplicate, dump or restore'))
    parser.add_argument('-d', '--database', type=str, required=True,
                        help='the targetted database')
    parser.add_argument('-pw', '--password', type=str, required=True,
                        help='the odoo superadmin password')
    parser.add_argument('-dm', '--demo', type=str, default='False',
                        help='demonstration data')
    parser.add_argument('-l', '--lang', type=str, default='fr_FR',
                        help='default language')
    parser.add_argument('-dbpw', '--database_password', type=str, default='admin',
                        help='the database admin password, default to admin')
    parser.add_argument('-dp', '--dump-path', type=str, default='/tmp/',
                        help='the absolute path where to dump the database, '
                        'defaults to /tmp/')
    parser.add_argument('-dfp', '--dump-full-path', type=str,
                        help='the absolute full path where to dump the database, '
                        'used if given, else dump path is used')
    parser.add_argument('-dt', '--database-target', type=str,
                        help=('name for duplicated or restore targetted database '
                              ' (optional : name_copy otherwise'))
    parser.add_argument('-rc', '--restore-copy', type=bool, default=False,
                        help=('Is restore a copy or a move ? Defaults to False, '
                              'then move'))
    parser.add_argument('-th', '--target-host', type=str,
                        help='targetted host, per default equal host')
    parser.add_argument('-tpw', '--target-password', type=str,
                        help='the targeted host odoo superadmin password')
    parser.add_argument('-tpp', '--target-port', type=str,
                        help='the targeted host port')

    args = parser.parse_args()
    # Connection
    odoo = common.connection(args)

    # Databases actions
    dblist = odoo.db.list()
    if args.action == 'create' or args.action == 'restore':
        if args.database in dblist:
            print 'database already exists'
        else:
            if args.action == 'create':
                odoo.db.create(args.password, args.database, str2bool(args.demo),
                               args.lang, args.database_password)
            elif args.action == 'restore':
                restore(odoo, args)
    else:
        if args.database not in dblist:
            print 'database not found'
        elif args.action == 'drop':
            odoo.db.drop(args.password, args.database)
        elif args.action == 'duplicate': # local or remote
            name = args.database_target or args.database + '_copy'
            if args.target_host and args.target_port and args.target_password:
                dump(odoo, args)
                restore(odoo, args)
            else:
                odoo.db.duplicate(args.password, args.database, name)
        elif args.action == 'dump':
            dump(odoo, args)

if __name__ == "__main__":
    main()
