from java import util
from java import io
from java.lang import String

def undeployCdsEnterpriseApp(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl):
    connect(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl)
    cd("AppDeployments")
    for i in ls().split() : 
        if( i.count('cdsn-ear') > 0 ) :
            undeploy(i)
    disconnect()
# end undeployCdsEnterpriseApp()

def doBounceWeblogic(cdsAppAdminUrl, cdsAppDomainName, cdsNodeMgrPort, cdsAppAdminUsername, cdsAppAdminPwd, cdsAppTargetServer, cdsAppDomainDir, applicationName, applicationFilePath):
    print 'Bouncing Weblogic Server'
    
    hostNameStartIndex=String(cdsAppAdminUrl).indexOf("//")
    hostNameStopIndex=String(cdsAppAdminUrl).indexOf(":",hostNameStartIndex)
    hostName=String(cdsAppAdminUrl).substring(hostNameStartIndex+2,hostNameStopIndex)
    
    if (cdsAppTargetServer != (cdsAppDomainName+'.admin')): 
      '''SHUTDOWN Managed Servers'''

      nmPort=cdsNodeMgrPort
      if nmPort is None:
      	nmPort='5559'

      nmConnect(cdsAppAdminUsername, cdsAppAdminPwd, hostName, nmPort, cdsAppDomainName, cdsAppDomainDir,cdsNmType )
      
      nmKill(cdsAppTargetServer) 
      nmStart(cdsAppTargetServer)    
    
      nmDisconnect();
    else: 
      '''SHUTDOWN and RESTART Admin Server, if Admin Server is the Target'''
      shutdown(cdsAppDomainName+'.admin','Server')
      startServer(cdsAppTargetServer, cdsAppDomainName, cdsAppAdminUrl, cdsAppAdminUsername, cdsAppAdminPwd, cdsAppDomainDir)
#end bounceWeblogic()
    
def deployCdsEnterpriseApp(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl):
    connect(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl)
    cd("AppDeployments")
    deploy(applicationName, applicationFilePath, cdsAppTargetServer, upload='true')
    startApplication(applicationName)
    disconnect()
#end deployCdsEnterpriseApp()

#runPropertiesPath = sys.argv[1]
bounceWeblogic = sys.argv[1]
applicationName = sys.argv[2]
applicationFilePath = sys.argv[3]
cdsAppAdminUsername = sys.argv[4]
cdsAppAdminPwd = sys.argv[5]
cdsAppAdminUrl = sys.argv[6]
cdsAppTargetServer = sys.argv[7]
cdsAppDomainName = sys.argv[8]
cdsNodeMgrPort = sys.argv[9]
cdsAppDomainDir = sys.argv[10]
cdsNmType = sys.argv[11]

#props = util.Properties();
#fis = io.FileInputStream(io.File(runPropertiesPath));
#props.load(fis);

# undeploy any CDS EAR that is currently deployed.
undeployCdsEnterpriseApp(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl)

# bounce the server if requested
if(bounceWeblogic == 'True'):
    doBounceWeblogic(cdsAppAdminUrl, cdsAppDomainName, cdsNodeMgrPort, cdsAppAdminUsername, cdsAppAdminPwd, cdsAppTargetServer, cdsAppDomainDir, applicationName, applicationFilePath)

# deploy the CDS EAR to the target server.
deployCdsEnterpriseApp(cdsAppAdminUsername, cdsAppAdminPwd, cdsAppAdminUrl)

exit()
