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

def undeployArsEnterpriseApp(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl):
    connect(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl)
    cd("AppDeployments")
    for i in ls().split() : 
        if( i.count('ars-ear') > 0 ) :
            undeploy(i)
    disconnect()
# end undeployArsEnterpriseApp()

def doBounceWeblogic(arsAppAdminUrl, arsAppDomainName, arsNodeMgrPort, arsAppAdminUsername, arsAppAdminPwd, arsAppTargetServer, arsAppDomainDir, applicationName, applicationFilePath):
    print 'Bouncing Weblogic Server'
    
    hostNameStartIndex=String(arsAppAdminUrl).indexOf("//")
    hostNameStopIndex=String(arsAppAdminUrl).indexOf(":",hostNameStartIndex)
    hostName=String(arsAppAdminUrl).substring(hostNameStartIndex+2,hostNameStopIndex)
    
    if (arsAppTargetServer != (arsAppDomainName+'.admin')): 
      '''SHUTDOWN Managed Servers'''

      nmPort=arsNodeMgrPort
      if nmPort is None:
      	nmPort='5556'
 
	nmConnect(arsAppAdminUsername, arsAppAdminPwd, hostName, nmPort, arsAppDomainName)
      
      	nmKill(arsAppTargetServer) 
      	nmStart(arsAppTargetServer)   
    
      nmDisconnect();
    else: 
      '''SHUTDOWN and RESTART Admin Server, if Admin Server is the Target'''
      shutdown(arsAppDomainName+'.admin','Server')
      startServer(arsAppTargetServer, arsAppDomainName, arsAppAdminUrl, arsAppAdminUsername, arsAppAdminPwd, arsAppDomainDir)

#end bounceWeblogic()
    
def deployArsEnterpriseApp(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl):
    connect(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl)
    cd("AppDeployments")
    deploy(applicationName, applicationFilePath, arsAppTargetServer, upload='true')
    startApplication(applicationName)
    disconnect()
#end deployArsEnterpriseApp()

#runPropertiesPath = sys.argv[1]
bounceWeblogic = sys.argv[1]
applicationName = sys.argv[2]
applicationFilePath = sys.argv[3]
arsAppAdminUsername = sys.argv[4]
arsAppAdminPwd = sys.argv[5]
arsAppAdminUrl = sys.argv[6]
arsAppTargetServer = sys.argv[7]
arsAppDomainName = sys.argv[8]
arsNodeMgrPort = sys.argv[9]
arsAppDomainDir = sys.argv[10]

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

# undeploy any ARS EAR that is currently deployed.
undeployArsEnterpriseApp(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl)

# bounce the server if requested
if(bounceWeblogic == 'True'):
    doBounceWeblogic(arsAppAdminUrl, arsAppDomainName, arsNodeMgrPort, arsAppAdminUsername, arsAppAdminPwd, arsAppTargetServer, arsAppDomainDir, applicationName, applicationFilePath)

# deploy the ARS EAR to the target server.
deployArsEnterpriseApp(arsAppAdminUsername, arsAppAdminPwd, arsAppAdminUrl)

exit()
