#! /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, socket, os, sys, 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):
        import socket
        result = socket.gethostbyaddr(hostname)
        if result: hostname = result[0]
    return hostname

def do_bconsole_config(bc):
    for x in bc.do_sql('SELECT name FROM %s' % bacula_tools.Director.table):
        d = bacula_tools.Director().search(x)
        print(d.bconsole())
    return

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]))

q = cgi.FieldStorage()
bc = bacula_tools.Bacula_Factory()

if 'bconsole' in os.environ.get('PATH_INFO',''): do_bconsole_config(bc)
else:
    guest = fix_hostname(q.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 = q.getvalue('director', '')
        bacula_tools.default_jobs(client)
        bacula_tools.default_director(client, dname)
    print(client.fd())
    for id in bc.do_sql('SELECT director_id FROM client_pwords where client_id = %s ORDER BY director_id', client[bacula_tools.ID]):
        print( bacula_tools.Director(client_id = client[bacula_tools.ID]).search(id).fd())
    
    for id in bc.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(id))


