#!/usr/bin/env python

# get client properties for bacula

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
#

try:
    clientsWithBacula=json.loads( subprocess.check_output( opsiCallPrefix + opsiCallClientsWithBacula ) )
except subprocess.CalledProcessError:
    print "failed"
    exit( 1 )

pprint( clientsWithBacula )
        
for client in clientsWithBacula:
    clientId = client['clientId']
    print clientId
    
    try:
        clientBaculaProperties=json.loads( subprocess.check_output( opsiCallPrefix + opsiCallClientBaculaProperties + [ client['clientId'] ] ) )
    except subprocess.CalledProcessError:
        print "failed"
        exit( 1 )
        
    pprint( clientBaculaProperties )
    write_client_conf( client, clientBaculaProperties )
    write_job_conf( client, clientBaculaProperties )
