#!/usr/bin/env python

# -*- coding: utf-8 -*-

"""ospi-client: performs operation for opsi clients on opsi server via JSON-RPC."""

__author__ = "Joerg Steffens"
__copyright__ = "Copyright 2012, dass IT GmbH"
__license__ = "GPL"
__version__ = "1.1"
__email__ = "joerg.steffens@dass-it.de"

#self.command("opsi-admin -d method host_createOpsiClient "+ \
        #computername + " null " + "\\'"+description+"\\'" + \
        #" \\'created by dassadmin\\' " + mac_address + " " + \
        #ip_address)
#self.command("opsi-admin -d method configState_create clientconfig.depot.id " + \
        #computername + " " + depotName)                        
                        
import argparse
import jsonrpc
import logging
import os
from pprint import pprint
import time

UrlJsonRpc="https://<username>:<password>@opsi:4447/rpc"

HelpEpilog="WARNING: python-json-rpc is known to have problems with HTTP proxies. In case of problems, make sure, the environment variables http_proxy and/or https_proxy are *not* set."

class OpsiRpc:

    UrlJsonRpcDefault="https://opsi:4447/rpc"
    
    ProductAttributesCopy = ['actionRequest','actionResult','installationStatus','packageVersion','productVersion']
    
    def __init__(self, urlJsonRpc = UrlJsonRpcDefault, debug=False ):
        self.logger=logging.getLogger(__name__)        
        self.debug=debug
        self.urlJsonRpc=urlJsonRpc
        self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
        self.logger.debug( "initialized: " + self.urlJsonRpc )

        
    def list(self):
        print( "\n".join( self.rpc.getClientIds_list() ) )
        return True

        
    def getClientsWithProduct( self, product ):
        return self.rpc.productOnClient_getObjects( [], { "productId": product, "installationStatus": "installed" } )


    def listClients( self, product ):
        if product:
            for client in self.getClientsWithProduct( product ):
                print client['clientId']
        else:
            return self.list()
        return True
        
        
    def exists(self, src):
        return len( self.rpc.host_getObjects( [], {"id":src} ) ) == 1
        
    def info(self, src):
        if not self.exists( src ):
            print "failed: opsi client", src, "does not exist"
            return False
        print src + ":"
        host = self.rpc.host_getHashes( [], {"id":src} )[0]
        print "  IP:", host["ipAddress"]
        print "  MAC:", host["hardwareAddress"]
        print "  inventory:", host["inventoryNumber"]
        print "  last seen:", host["lastSeen"]
        print "  notes:", host["notes"]
        
        print "  products:"
        products = self.getProductOnClient( src, [] )
        for i in products:
            print "    " + i['productId'] + ":"
            print "      " + i['installationStatus'], "(",
            if i['actionRequest']:
                print i['actionRequest'],
                if i['actionProgress']:
                    print i['actionProgress'],
            print ")"
            print "      ",
            pprint( i, indent=8 )
        return True

    def clean(self, src):
        if not self.exists( src ):
            return False
        products = self.rpc.productOnClient_getObjects( [], { 'clientId': src } )
        self.rpc.productOnClient_deleteObjects( products )

        products = self.rpc.productPropertyState_getObjects( [], { 'objectId': src } )
        self.rpc.productPropertyState_deleteObjects( products )
        
        if self.debug:
            pprint( self.getProductOnClient( src ) )
        return True
        
    def createClient(self, name, opsiHostKey, description, notes, hardwareAddress, ipAddress):
        self.rpc.host_createOpsiClient( name, opsiHostKey, description, notes, hardwareAddress, ipAddress )

    def clientSetDepot(self, name, depot):
        self.rpc.configState_create( "clientconfig.depot.id", name, depot )        

    def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None, description = "", copyProperties = True ):
    
        print "create/update", dst, "from template", src + ":",
        obj = {
          "id" : dst,
          "type" : "OpsiClient",
          "notes" : "copy of " + src,
          "description" : description,
          #"inventoryNumber" : "",
        }
        if hardwareAddress:
            obj['hardwareAddress'] = hardwareAddress
        if ipAddress:
            obj['ipAddress'] = ipAddress

        if self.exists( dst ):
            self.rpc.host_updateObject(obj)
        else:
            self.rpc.host_insertObject(obj)
            
        if depot:
            self.clientSetDepot(dst,depot)
            
        if self.debug:
            pprint( self.getProductOnClient( src ) )
        self.copyProductOnClient( src, dst )
        # TODO: 
        #  copy product properties:
        #  opsiCallClientBaculaProperties=[ "method", "getProductProperties_hash", "bacula" ]
        if copyProperties:
            if self.debug:
                print "copy product properties"
            self.copyProductPropertyState( src, dst )
        print "done"
        return True



    def getProductOnClient( self, client, attributes = ProductAttributesCopy ):
        return self.rpc.productOnClient_getHashes( [], { 'clientId': client } )



    def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
        products_src = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
        products_dst = []
        for i in products_src:
            if self.debug: 
                print i['productId']
                pprint( i )
            i['clientId'] = dst
            products_dst.append(i)
        self.rpc.productOnClient_createObjects( products_dst )
        if self.debug:
            pprint( self.getProductOnClient( dst ) )

    def getProductPropertyState( self, client, attributes = [] ):
        return self.rpc.productPropertyState_getHashes( [], { 'objectId': client } )
                        
    def copyProductPropertyState( self, src, dst, attributes = [] ):
        productProperties_src = self.getProductPropertyState( src, attributes )
        productProperties_dst = []
        for i in productProperties_src:
            if self.debug: 
                print i['productId'], "-", i["propertyId"] + ": ",
                pprint(i["values"])
                #pprint( i )
            i['objectId'] = dst
            productProperties_dst.append(i)
        self.rpc.productPropertyState_createObjects( productProperties_dst )
        if self.debug:
            pprint( self.getProductPropertyState( dst ) )


    def getClientProductProperty( self, client, product ):
        return self.rpc.getProductProperties_hash( product, [ client ] )

    def write_client_conf( self, fd, 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", "FileRetention", "JobRetention", "AutoPrune" ]
        fd.write( "Client {\n" )
        fd.write( '  Name     = "' + properties['filedaemon_full_name'] + '"' + "\n" )
        fd.write( '  Address  = "' + client['clientId'] + '"' + "\n" )
        # ipAddress: method host_getObjects [] '{"id":client['clientId']}'
        #print "  # Address =", ipAddress
        fd.write( '  Password = "' + properties['filedaemon_full_password'] + '"' + "\n" )
        try:
            catalog = properties['catalog']
        except KeyError:
            catalog = "MyCatalog"
        fd.write( '  Catalog  = "' + catalog + '"' + "\n" )
        for i in params:
            try:
                fd.write( '  ' + i + ' = "' + properties[i.lower()] + '"' + "\n" )
            except KeyError:
                fd.write( '  # ' + i + " = \n" )
        fd.write( "}\n")
        fd.write( "\n" )
        
        


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


    def write_config_file_header( self, fd ):
        try:        
            fd.write( "#\n" )
            fd.write( "# automatically generated at {}\n".format( time.asctime() ) )
            fd.write( "#\n\n" )
        except BaseException as e:        
            self.logger.exception( "failed to create files" )
            return False
        return True
            

    def createBaculaConfigFiles( self ):
        clientsWithBacula=self.getClientsWithProduct( "bacula" )
        if clientsWithBacula:
            try:
                file_opsi_clients = open('opsi-clients-generated.conf', 'w')
                self.write_config_file_header( file_opsi_clients )
                
                file_opsi_jobs = open('opsi-jobs-generated.conf', 'w')
                self.write_config_file_header( file_opsi_jobs )
            except BaseException as e:        
                self.logger.exception( "failed to create files" )
                return False
            for client in clientsWithBacula:
                clientId = client['clientId']                
                try:
                    clientBaculaProperties=self.getClientProductProperty( clientId, "bacula" )
                except ValueError as e:
                    self.logger.warn( "%s: no valid information found: %s" %(clientId, e) )
                else:
                    if clientBaculaProperties:
                        #pprint( clientBaculaProperties )
                        self.write_client_conf( file_opsi_clients, client, clientBaculaProperties )
                        self.write_job_conf( file_opsi_jobs, client, clientBaculaProperties )
                        self.logger.info( "%s: OK" % clientId )
                    else:
                        self.logger.warn( "%s: failed: no product properties defined" %(clientId) )
            return True



if __name__ == '__main__':
    logging.basicConfig(format='%(message)s')
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    
    parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.', epilog=HelpEpilog )

    parser.add_argument( '--debug', action='store_true', help="enable debugging output" )

    parser_url = parser.add_mutually_exclusive_group(required=True)
    parser_url.add_argument( '--url', help="OPSI Server JSON-RPC url, in following format: " + UrlJsonRpc )
    
    parser_url.add_argument( '--server', help="OPSI Server (instead of URL)" )
    username_default=os.getlogin()
    
    parser.add_argument( '--username', help="username (instead of URL), default: " + username_default, default=username_default )
    parser.add_argument( '--password', help="password (instead of URL)" )
    
    subparsers = parser.add_subparsers(title='subcommands',
        description='valid subcommands',
        help='additional help',
        dest='subcommand' )

    parser_clean = subparsers.add_parser('clean', help='remove all product states from a opsi client' )
    parser_clean.add_argument( 'src', help="source opsi client to clean" )
                
    parser_copy = subparsers.add_parser('copy', help='copy/create a opsi client from a template opsi client')    
    parser_copy.add_argument( 'src', help="source/template opsi client" )
    parser_copy.add_argument( 'dst', help="opsi client to be created" )
    parser_copy.add_argument( '--ip', help="IP address of the new opsi client" )
    parser_copy.add_argument( '--mac', help="MAC address of the new opsi client" )
    parser_copy.add_argument( '--depot', help="depot server the new opsi client should be located" )
    #parser_copy.add_argument( '--no-properties', action='store_false', help="don't copy product properties" )
        
    parser_createBaculaConfigFiles = subparsers.add_parser('createBaculaConfigFiles', help='create Bacula config files for all clients that have bacula installed')

    parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
    parser_exists.add_argument( 'src', help="source opsi client" )
    
    #parser_list = subparsers.add_parser('list', help='list all opsi clients' )
    
    parser_listClients = subparsers.add_parser('listClients', help='list opsi clients')
    parser_listClients.add_argument( '--product', help="only list clients, that have product installed" )
    
    parser_info = subparsers.add_parser('info', help='print information about a opsi client' )
    parser_info.add_argument( 'src', help="opsi client" )
    
    args = parser.parse_args()
    
    if args.debug:
        logger.setLevel(logging.DEBUG)

    url=args.url
    if (not url):
        if args.server:
            account=""
            if args.username and args.password:
                account=args.username + ":" + args.password + "@"
            elif args.username:
                account=args.username + "@"
            url="https://" + account + args.server + ":4447/rpc"
        else:
            parser.error( "argument --url is required" )
        
    opsi=OpsiRpc( url, args.debug )
    
    result = True

    if args.subcommand == "clean":
        result = opsi.clean( args.src )
    elif args.subcommand == "copy": 
        result = opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
    elif args.subcommand == "createBaculaConfigFiles": 
        result = opsi.createBaculaConfigFiles()
    elif args.subcommand == "exists":
        result = opsi.exists( args.src )        
    elif args.subcommand == "list":
        result = opsi.list()
    elif args.subcommand == "listClients":         
        result = opsi.listClients( args.product )        
    elif args.subcommand == "info":
        result = opsi.info( args.src )        
    else:
        print "not yet implemented"

    if args.debug: print result    
        
    if result:
        exit(0)
    else:
        exit(1)
