#! /usr/bin/env python
'''CGI that returns bconsole and bacula-fd configurations.

It can handle a couple parameters:
	hostname: if passed, the CGI will use this as the hostname to work
	with instead of using socket calls to determine the client
	hostname.

	bconsole: return a bconsole.conf instead of a bacula-fd.conf

Install it someplace your clients will be able to hit, and grant it INSERT
and SELECT privileges in your configuraiton database.

You should also create a place for python to use for an egg cache, writable
only by your web server user, and ensure that PYTHON_EGG_CACHE points there.

'''
from __future__ import print_function

import cgi
import socket
import os
import sys
import re
os.environ.setdefault('PYTHON_EGG_CACHE', '/tmp')

# Only keep these two lines while doing development
import cgitb
cgitb.enable(display=2, logdir="/tmp")

import bacula_tools


def fix_hostname(hostname):
    '''Check for getting an IP address and, if so, turn it into a hostname'''
    if re.match(r'\d+\.\d+\.\d+\.\d+', hostname):
        result = socket.gethostbyaddr(hostname)
        if result:
            hostname = result[0]
    return hostname


def do_bconsole_config(bacula_config_object):
    '''Print out the bconsole configuration(s)'''
    for director_name in bacula_config_object.do_sql('SELECT name FROM %s' % bacula_tools.Director.table):
        this_director = bacula_tools.Director().search(director_name)
        print(this_director.bconsole())
    return


def main():
    '''Main entry point.'''
    print('Content-type: text/plain; charset=iso-8859-1\r\n\r\n')
    print('''
    # Host Config file generated by %s on %s.
    #
    #DO NOT EDIT THIS FILE BY HAND
    ''' % (sys.argv[0], os.uname()[1]))

    query_variables = cgi.FieldStorage()
    bacula_config_object = bacula_tools.Bacula_Factory()

    if 'bconsole' in os.environ.get('PATH_INFO', ''):
        do_bconsole_config(bacula_config_object)
    else:
        guest = fix_hostname(query_variables.getvalue('hostname', os.environ.get(
            'REMOTE_HOST', os.environ.get('REMOTE_ADDR', 'localhost.localdomain'))))
        client = bacula_tools.Client(
            {bacula_tools.NAME: bacula_tools.hostname_mangler(guest)}).search()
        if not client[bacula_tools.ID]:
            client.set(bacula_tools.ADDRESS, guest)
            dname = query_variables.getvalue('director', '')
            bacula_tools.default_jobs(client)
            bacula_tools.default_director(client, dname)
        print(client.fd())
        for director_id in bacula_config_object.do_sql('SELECT director_id FROM pwords where obj_id = %s and obj_type = %s ORDER BY director_id', (client[bacula_tools.ID], client.IDTAG)):
            print(bacula_tools.Director(
                client_id=client[bacula_tools.ID]).search(director_id).fd())

        for messages_id in bacula_config_object.do_sql('SELECT messages_id FROM messages_link WHERE ref_id = %s AND link_type = %s', (client[bacula_tools.ID], client.IDTAG)):
            print(bacula_tools.Messages().search(messages_id))


if __name__ == '__main__':
    main()
