#!/usr/bin/env python

# Skript erstellen, dass ein OPSI-Rechner-Eintrag kopiert.
# D.h. die Produkte, Anforderung.
# Ggf. optional Stand und ggf. Versionsnummer
# Ggf. optional ProductProperties

                #self.command("opsi-admin -d method host_createOpsiClient "+ \
                        #computername + " null " + "\\'"+description+"\\'" + \
                        #" \\'created by dassadmin\\' " + mac_address + " " + \
                        #ip_address)
                #method host_createOpsiClient id *opsiHostKey *description *notes *hardwareAddress *ipAddress *inventoryNumber *oneTimePassword *created *lastSeen
                #self.command("opsi-admin -d method configState_create clientconfig.depot.id " + \
                        #computername + " " + depotName)                        
                        
import argparse
import jsonrpc
from pprint import pprint

UrlJsonRpc="https://joergs:linuxlinux@opsi4.joergs.dass-it:4447/rpc"

class OpsiRpc:
    
    ProductAttributesCopy = ['actionRequest','actionResult','installationStatus','packageVersion','productVersion']
    
    def __init__(self, urlJsonRpc, debug=False ):
        self.debug=debug
        self.urlJsonRpc=urlJsonRpc
        self.rpc=jsonrpc.ServiceProxy(self.urlJsonRpc)
        
    def dump(self):
        print self.urlJsonRpc
        print self.rpc.getClientIds_list()
        
    def copyClient( self, src, dst, ipAddress = None, hardwareAddress = None, depot = None ):
    
        print "create/update", dst, "from template", src + ":",
        #method host_createOpsiClient id *opsiHostKey *description *notes *hardwareAddress *ipAddress *inventoryNumber *oneTimePassword *created *lastSeen
        #id=dst
        opsiHostKey=None
        description=""
        notes="copy of " + src
        self.rpc.host_createOpsiClient( dst, opsiHostKey, description, notes, hardwareAddress, ipAddress )
        if depot:
            self.rpc.configState_create( "clientconfig.depot.id", dst, depot )        
        if self.debug:
            self.productOnClient( src )
        self.copyProductOnClient( src, dst )
        # TODO: 
        #  copy product properties:
        #  opsiCallClientBaculaProperties=[ "method", "getProductProperties_hash", "bacula" ]
        print "done"

        
    def productOnClient( self, client, attributes = ProductAttributesCopy ):
        #pprint( self.rpc.productOnClient_getObjects( [], { 'clientId': client } ) )
        #pprint( self.rpc.productOnClient_getHashes( attributes, { 'clientId': client } ) )
        pprint( self.rpc.productOnClient_getHashes( [], { 'clientId': client } ) )
        
    def copyProductOnClient( self, src, dst, attributes = ProductAttributesCopy ):
        products = self.rpc.productOnClient_getHashes( attributes, { 'clientId': src } )
        for i in products:
            if self.debug: 
                pprint( i )
                print i['productId']
            i['clientId'] = dst
            self.rpc.productOnClient_createObjects( i )
            if self.debug:
                self.productOnClient( dst )
        


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Command line tool for OPSI configuration.')
    parser.add_argument( '--debug', action='store_true', help="enable debugging output" )
    #parser.add_argument( '--verbose', type=bool, help="add debugging output" )
    parser.add_argument( '--url', help="OPSI Server JSON-RPC url, normally https://<username>:<password>@<OPSI-SERVER>:4447/rpc" )

    subparsers = parser.add_subparsers(title='subcommands',
        description='valid subcommands',
        help='additional help',
        dest='subcommand' )

    parser_list = subparsers.add_parser('list', help='list all opsi clients' )

    parser_exists = subparsers.add_parser('exists', help='check, if a opsi clients exists' )
    parser_exists.add_argument( 'src', help="source opsi client" )
    
    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_bar.set_defaults(func=bar)
    #>>> # parse the args and call whatever function was selected
    #>>> args = parser.parse_args('bar XYZYX'.split())
    #>>> args.func(args)    
    
    
    args = parser.parse_args()
    
    
    urlJsonRpc = UrlJsonRpc
    if args.url:
        urlJsonRpc = args.url
    
    opsi=OpsiRpc( urlJsonRpc, args.debug )
    
    if args.subcommand == "copy": 
        opsi.copyClient( args.src, args.dst, args.ip, args.mac, args.depot )
    else:
        print "not yet implemented"

    if args.debug: print "end"
    