#!/usr/bin/python2
#
# Copyright (c) 2013-2015 Rafael Martinez Guerrero / PostgreSQL-es
# rafael@postgresql.org.es / http://www.postgresql.org.es/
#
# Copyright (c) 2015 USIT-University of Oslo
#
# This file is part of Pgbackman
# https://github.com/rafaelma/pgbackman
#
# PgBackMan is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PgBackMan 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 Pgbackman.  If not, see <http://www.gnu.org/licenses/>.

import argparse
from pgbackman.cli import *

if __name__ == '__main__':

    try:

        #
        # Processing command line parameters
        #

        output_format = ''
        pgbackman_command = ''

        parser = argparse.ArgumentParser(prog=sys.argv[0], description='zabbix-cli - Zabbix client')

        parser.add_argument('--output', '-o',  metavar='[csv|json]', choices=['csv', 'json'],
                            required=False, dest='output_format')

        parser.add_argument('--command', '-C', metavar='<PgBackMan command>', required=False, dest='pgbackman_command')
        
        args = parser.parse_args()  
        
        if args.output_format:
            output_format = args.output_format 
    
        if args.pgbackman_command:
            pgbackman_command = args.pgbackman_command 

        #
        # pgbackman cli initialization
        #

        cli = PgbackmanCli()
        
        #
        # Processing output format
        #
    
        if output_format == 'csv':
            cli.output_format = 'csv'
            
        elif output_format == 'json':
            cli.output_format = 'json'
            
        else:
            cli.output_format = 'table'

        #
        # PgBackMan in non-interactive modus
        #

        if pgbackman_command != '':
            
            cli.execution_modus = 'non-interactive'
            cli.onecmd(pgbackman_command)

        #
        # PgBackMan in interactive modus (pgbackman-shell)
        #

        elif pgbackman_command == '':
            os.system('clear')

            cli.execution_modus = 'interactive'

            cli.check_pgbackman_database_version()
            cli.cmdloop()
        
        else:
            raise NotImplementedError
        
    except KeyboardInterrupt:
        print
        print "\nDone, thank you for using PgBackMan"

        sys.exit(0)
