#!/usr/bin/python2
#
# Copyright (c) 2013-2015 Rafael Martinez Guerrero / PostgreSQL-es
# rafael@postgresql.org.es / http://www.postgresql.org.es/
#
# Copyright (c) 2014-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 PgBck.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os
import signal
import argparse
import json

from pgbackman.database import * 
from pgbackman.config import *
from pgbackman.logs import *


'''
This program is used to generate the JSON output that Zabbix needs
in a low-level discovery rule.

The JSON output will have information about the databases with a
backup definition in PgBackMan. {#PGSQL_NODE} and {#DBNAME} are the
macros Zabbix will use to get the data.

'''

# ############################################
# Function signal_handler()
# ############################################
    
def signal_handler(signum, frame):
    sys.exit(0)


# ############################################
# Function Main()
# ############################################
    
def get_pgbackman_zabbix_autodiscovery(backup_server_fqdn):

    backup_definitions_list = []

    try:

        conf = PgbackmanConfiguration()
        pgbackman_dsn = conf.dsn
        
        db = PgbackmanDB(pgbackman_dsn, 'pgbackman_zabbix_autodiscovery')

        backup_server_id = db.get_backup_server_id(backup_server_fqdn)
        
        for def_id,pgsql_node,dbname in db.get_backup_server_bckdef_list(backup_server_id):
            backup_definition = {}
            backup_definition = {"{#DEFID}":def_id,"{#PGSQL_NODE}":pgsql_node,"{#DBNAME}":dbname}

            backup_definitions_list.append(backup_definition)
    
        result = {"data":backup_definitions_list}
        print json.dumps(result,sort_keys=True,indent=2)
    
        logs.logger.info('Zabbix autodiscovery data for backup server: [%s] delivered. (Total bckdef: %s)',backup_server_fqdn,len(backup_definitions_list))
    
    except Exception as e:
        logs.logger.error('Problems getting Zabbix autodiscovery data for backup server: [%s] - %s',args.backup_server_fqdn,e)
        sys.exit(1)

    
# ############################################
# 
# ############################################

if __name__ == '__main__':

    signal.signal(signal.SIGINT,signal_handler)
    signal.signal(signal.SIGTERM,signal_handler)

    #
    # Initializing logging
    #

    logs = PgbackmanLogs("pgbackman_zabbix_autodiscovery", "", "")
    logs.logger.info('**** pgbackman_zabbix_autodiscovery started. ****')

    parser = argparse.ArgumentParser(prog=sys.argv[0])
    parser.add_argument('--backup-server','-b', metavar='BACKUP-SERVER-FQDN', required=True, help='Backup server FQDN', dest='backup_server_fqdn')
    
    args = parser.parse_args()    
    
    if args.backup_server_fqdn:

        logs.logger.debug('Getting Zabbix autodiscovery data for backup server: [%s]',args.backup_server_fqdn)
        get_pgbackman_zabbix_autodiscovery(args.backup_server_fqdn)

    else:
        print('Backup server fqdn parameter not defined')
        logs.logger.error('Backup server fqdn parameter not defined')
    
    logs.logger.info('**** pgbackman_zabbix_autodiscovery finished. ****')
