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

from datetime import datetime
import argparse
import common


def datefmt():
    """ Get adapted date format """
    today = datetime.today()
    return today.strftime('%Y-%m-%d_%Hh%Mm%Ss')


def dump(odoo, bakpath, password, dbnames):
    """ Dumps a database list """
    for dbname in dbnames:
        dump = odoo.db.dump(password, dbname)
        fpath = '{bakpath}/{date}_{dbname}.zip'.format(bakpath=bakpath,
                                                       dbname=dbname,
                                                       date=datefmt())
        with open(fpath, 'wb') as zipf:
            zipf.write(dump.read())
    return True


def dump_all(odoo, bakpath, password):
    """ Dump all databases """
    return dump(odoo, bakpath, password, odoo.db.list())


def main():
    """ Main function with argument parsing """
    parser = argparse.ArgumentParser(description='Backup Odoo databases')
    parser = common.parser(parser)
    parser.add_argument('-pw', '--password', type=str, required=True,
                        help='the odoo master password')
    parser.add_argument('-D', '--directory', type=str, required=True,
                        help='the directory path where to save backups')
    parser.add_argument('-n', '--names', type=str,
                        help='optional database names (default:all)')
    args = parser.parse_args()

    # Connection
    odoo = common.connection(args)

    # Backup actions
    if not args.names:
        dump_all(odoo, args.directory, args.password)
    else:
        dump(odoo, args.directory, args.password, args.names.split(','))

if __name__ == "__main__":
    main()
