#!/usr/bin/python

from bcfg import *
import resource
import directive
import ResourceInfo

import sys
import random

def genpasswd(len=32):
    charset="01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!/%()=?@"
    password=""
    for a in xrange(0,len):
       password += random.choice(charset)
    return password


def createClientConfig(dirdcfg,clientName,clientPassword=genpasswd()):
    director=dirdcfg.getRoot().getByType("Director")[0]
    dirdName=director.getName()
    r=dirdcfg.getRoot().getByName(clientName)
    if len(r)==1:
        client=r[0]
    else:
        return
    
    filename=clientName+".conf"
    fdcfg=FiledConfig(filename)
    fdcfg.setDefaults(dirdName,clientPassword,clientName)
    fdcfg.write()

def createAllClientConfigs(dirdcfg):
    clients=dirdcfg.getRoot().getByType("Client",1)
    director=dirdcfg.getRoot().getByType("Director")[0]
    dirdName=director.getName()

    for c in clients:
        print c
        clientName=c.getName()
        if clientName!=None:
            r=c.getByType("Password")
            if len(r)>0:
                clientPassword=r[0].value
                clientPassword=clientPassword.replace('"','')
            else:
                clientPassword=""
            filename=clientName+".conf"
            fdcfg=FiledConfig(filename)
            fdcfg.setDefaults(dirdName,clientPassword,clientName)
            fdcfg.write()

def getDirectors():
    return [ "bacula-dir" ];

def loadDirectorConfig(filename):
    global currentConfig
    currentConfig=DirdConfig(filename)
    currentConfig.read()

def getDirectorConfig(directorName):
    global currentConfig
    return currentConfig

def getClients(directorName):
    return getResources(directorName,"Client")

def getResources(directorName,resType):
    dirdcfg=getDirectorConfig(directorName)
    resources=dirdcfg.getRoot().getByType(resType,1)
    result=[]
    for r in resources:
        result.append((r.id,r.getName()))
    return result

def keyValueList(res):
    result=[]
    for i in res.items:
        #if i.type=="Name":
        #    continue

        result.append((i.type,i.value))

    return result

def getResourceById(directorName,resId):
    dirdcfg=getDirectorConfig(directorName)
    return dirdcfg.getRoot().getById(resId)    

def getResourceByName(directorName,resType,name):
    dirdcfg=getDirectorConfig(directorName)
    return dirdcfg.getRoot().getByName(name,resType)[0]   

# main
if __name__ == "__main__":
    if len(sys.argv) < 2:
        filename="test.conf"
    else:
        filename=sys.argv[1]   

    loadDirectorConfig(filename)

    clientIds=getResources("bacula-dir","Client")
        
    c=getResourceById("bacula-dir",clientIds[0][0])
    print c
    print keyValueList(c)

