#!/usr/bin/env python3

import argparse
import logging
import os
import shlex
import subprocess
from pathlib import Path


LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
LOG_DATE = '%d/%m/%Y %H:%M:%S'
logging.addLevelName(logging.ERROR, '\033[1;41mERROR\033[1;0m')
logging.addLevelName(logging.DEBUG, '\x1b[33mDEBUG\033[1;0m')
logging.addLevelName(logging.INFO, '\x1b[32mINFO\033[1;0m')
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=LOG_DATE)
log = logging.getLogger(__name__)


PATH_SISTEMA = '/opt/empresa-libre'
PATH_BK = f'{Path.home()}/compartido/bkdb'


def _call(args):
    cmd = shlex.split(args)
    result = subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode()
    return result


def _join(*paths):
    return os.path.join(*paths)


def _actualizar():
    confirm = input('¿Estas seguro de actualizar (escribe si) ? ')
    if confirm != 'si':
        msg = 'Proceso de actualización cancelado'
        log.info(msg)
        return

    args = f'git -C {PATH_SISTEMA} pull origin master'
    _call(args)

    msg = 'Sistema actualizado correctamente'
    log.info(msg)
    return


def _backup():
    cmd = f'mkdir -p {PATH_BK}'
    _call(cmd)

    msg = 'Respaldando bases de datos...'
    log.info(msg)

    db_exclude = ('', 'postgres', 'template1', 'template0')
    args = 'psql -U postgres -t -c "select datname from pg_database"'
    result = _call(args).split('\n')
    clients = sorted([e.strip() for e in result if not e.strip() in db_exclude])

    cmd = 'pg_dump -U postgres -Fc {} -f "{}"'
    t = len(clients)
    for i, f in enumerate(clients):
        msg = f'\t{i+1:02} de {t} - BD: {f}'
        log.info(msg)

        path = _join(PATH_BK, f'{f}.bk')
        _call(cmd.format(f, path))
        log.info('\t\tRespaldada localmente...')

    msg = 'Base de datos respaldadas...'
    log.info(msg)
    return


def main(args):

    if args.actualizar:
        _actualizar()
        return

    if args.backup:
        _backup()
        return

    return


def _process_command_line_arguments():
    parser = argparse.ArgumentParser(
        description='Empresa Libre Util')
    parser.add_argument('-a', '--actualizar', dest='actualizar',
        action='store_true', default=False, required=False)
    parser.add_argument('-b', '--backup', dest='backup',
        action='store_true', default=False, required=False)
    return parser.parse_args()


if __name__ == '__main__':
    args = _process_command_line_arguments()
    main(args)
