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

""" Odoo backup script """

from datetime import datetime
import argparse
import httplib
import urllib
import common


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


def dump(odoo, args):
    """ Dumps a database list from API or HTTP call """
    for dbname in args.names.split(','):
        if args.alternative == 'no':
            dumpf = odoo.db.dump(args.password, dbname, args.format)
        else:
            conn = httplib.HTTPConnection(args.host, args.port)
            headers = {'User-Agent': ('Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) '
                                      'Gecko/20100101 Firefox/24.0'),
                       'Accept': 'text/plain'}
            if odoo.version != '8.0':
                params = urllib.urlencode({'master_pwd': args.password,
                                           'name': dbname,
                                           'backup_format': args.format})
                headers['Content-type'] = 'application/x-www-form-urlencoded'
                conn.request('POST', '/web/database/backup', params, headers)
            else:
                url = (u'/web/database/backup?backup_pwd=%s&backup_db=%s'
                       '&backup_format=%s&token=') % (args.password, dbname, args.format)
                conn.request('GET', url, '', headers)
            dumpf = conn.getresponse()
        fpath = '{bakpath}/{date}_{host}_{dbname}.{fmt}'.format(
            bakpath=args.directory, host=args.host, dbname=dbname,
            date=datefmt(), fmt=args.format
        )
        with open(fpath, 'wb') as zipf:
            zipf.write(dumpf.read())
        if args.alternative != 'no':
            conn.close()
    return True

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)')
    parser.add_argument('-f', '--format', type=str, default='zip',
                        help='optional database format (default:zip)')
    parser.add_argument('-alt', '--alternative', type=str, default='no',
                        help='alternative dump through HTTP calls (default:no)')
    args = parser.parse_args()

    # Connection
    odoo = common.connection(args)

    # Backup actions
    if not args.names:
        args.names = odoo.db.list()
    dump(odoo, args)

if __name__ == "__main__":
    main()
