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

def undeployApplication(adminUsername, adminPwd, cadminUrl, name):
    connect(adminUsername, adminPwd, adminUrl)
    cd("AppDeployments")
    for i in ls().split() : 
        if( i.count(name) > 0 ) :
            undeploy(i)
    disconnect()
# end undeployApplication()

def doBounceWeblogic(adminUrl, appDomainName, nodeMgrPort, adminUsername, adminPwd, appTargetServer, appDomainDir, applicationName, applicationFilePath):
    print 'Bouncing Weblogic Server'
    
    hostNameStartIndex=String(adminUrl).indexOf("//")
    hostNameStopIndex=String(adminUrl).indexOf(":",hostNameStartIndex)
    hostName=String(adminUrl).substring(hostNameStartIndex+2,hostNameStopIndex)
    
    if (appTargetServer != (appDomainName+'.admin')): 
      '''SHUTDOWN Managed Servers'''

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

      nmConnect(adminUsername, adminPwd, hostName, nmPort, appDomainName,appDomainDir,nmType)
      
      nmKill(appTargetServer) 
      nmStart(appTargetServer)    
    
      nmDisconnect();
    else: 
      '''SHUTDOWN and RESTART Admin Server, if Admin Server is the Target'''
      shutdown(appDomainName+'.admin','Server')
      startServer(appTargetServer, appDomainName, adminUrl, adminUsername, adminPwd, appDomainDir)
#end bounceWeblogic()
    
def deployApplication(adminUsername, adminPwd, adminUrl):
    connect(adminUsername, adminPwd, adminUrl)
    cd("AppDeployments")
    deploy(applicationName, applicationFilePath, appTargetServer, upload='true')
    startApplication(applicationName)
    disconnect()
#end deployApplication()

#runPropertiesPath = sys.argv[1]
bounceWeblogic = sys.argv[1]
applicationName = sys.argv[2]
applicationFilePath = sys.argv[3]
adminUsername = sys.argv[4]
adminPwd = sys.argv[5]
adminUrl = sys.argv[6]
appTargetServer = sys.argv[7]
appDomainName = sys.argv[8]
nodeMgrPort = sys.argv[9]
appDomainDir = sys.argv[10]
name = sys.argv[11]
nmType = sys.argv[12]

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

# undeploy any FPDS WAR that is currently deployed.
undeployApplication(adminUsername, adminPwd, adminUrl, name)

# bounce the server if requested
if(bounceWeblogic == 'True'):
    doBounceWeblogic(adminUrl, appDomainName, nodeMgrPort, adminUsername, adminPwd, appTargetServer, appDomainDir, applicationName, applicationFilePath)

# deploy the WAR to the target server.
deployApplication(adminUsername, adminPwd, adminUrl)

exit()
