#!/usr/bin/env python

# get client properties for bacula

import logging
import subprocess
import json
from pprint import pprint

opsi={
    'server': "https://degdepot2.joergs:4447/rpc",
    'username': "joergs",
    'password': "linuxlinux",
    }

# "-d"
opsiCallPrefix=[ "opsi-admin",  "-a", opsi['server'], "-u", opsi['username'], "-p", opsi['password'] ]

opsiCallClientsWithBacula=[ "method", "productOnClient_getObjects", "[]", '{"productId":"bacula", "installationStatus": "installed"}']

opsiCallClientBaculaProperties=[ "method", "getProductProperties_hash", "bacula" ]


def write_client_conf( client, properties ):
    #Client {
    #Name = ting-fd
    #Address = ting.dass-it
    #FDPort = 9102
    #Catalog = MyCatalog
    #Password = "D5w2V5w6B8a9H5Z"
    #File Retention = 6 months
    #Job Retention = 6 months
    #AutoPrune = yes
    #}
    params = [ "FDPort", "Catalog", "FileRetention", "JobRetention", "AutoPrune" ]
    print "Client {"
    print "  Name     =", properties['filedaemon_full_name']
    print "  Address  =", client['clientId']
    # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
    #print "  # Address =", ipAddress
    print "  Password =", properties['filedaemon_full_password']
    for i in params:
        try:
            print " " + i + " = " + properties[i.lower()]
        except KeyError:
            print "  # " + i + " = "
    print "}"
    print
    
    


def write_job_conf( client, properties ):
    #Job {
    #FileSet = "tingfileset"
    #Name = "ting"
    #Client = ting-fd
    #JobDefs = "LaptopJob"
    ## Write Bootstrap = "/var/lib/bacula/ting.bsr"
    #}
    params = [ "Fileset", "JobDefs" ]
    print "Job {"
    print "  Name    =", client['clientId'] + "-job"
    print "  Client  =", properties['filedaemon_full_name']
    for i in params:
        print " ",
        try:
            if not properties[i.lower()]:
                print "#",
            print i + " = " + properties[i.lower()]
        except KeyError:
            print "# " + i + " = "
    print "}"
    print

    

#
# main
#

#logging.basicConfig(format='%(asctime)s %(levelname)8s %(message)s')
logging.basicConfig(format='%(message)s')
logger = logging.getLogger(__name__)
#logger.setLevel(logging.INFO)
logger.setLevel(logging.DEBUG)

logger.debug( "start" )

try:
    clientsWithBacula=json.loads( subprocess.check_output( opsiCallPrefix + opsiCallClientsWithBacula ) )
#except subprocess.CalledProcessError as e:
except e:
    logger.exception( "%s: failed:" %(clientId) )
    exit(1)

#pprint( clientsWithBacula )
        
for client in clientsWithBacula:
    clientId = client['clientId']
    
    try:
        clientBaculaProperties=json.loads( subprocess.check_output( opsiCallPrefix + opsiCallClientBaculaProperties + [ client['clientId'] ] ) )
    except ValueError as e:
        logger.warn( "%s: no valid information found: %s" %(clientId, e) )
    except subprocess.CalledProcessError as e:
        logger.exception( "%s: failed:" %(clientId) )
        #exit( 1 )
    else:            
        #pprint( clientBaculaProperties )
        write_client_conf( client, clientBaculaProperties )
        write_job_conf( client, clientBaculaProperties )
        logger.info( "%s: OK" % clientId )

logger.debug( "finished" )
