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

def undeployTfsEnterpriseApp(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl):
    connect(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl)
    cd("AppDeployments")
    for i in ls().split() : 
        if( i.count('tfs-ear') > 0 ) :
            undeploy(i)
    disconnect()
# end undeployTfsEnterpriseApp()

def doBounceWeblogic(tfsAppAdminUrl, tfsAppDomainName, tfsNodeMgrPort, tfsAppAdminUsername, tfsAppAdminPwd, tfsAppTargetServer, tfsAppDomainDir, applicationName, applicationFilePath):
    print 'Bouncing Weblogic Server'
    
    hostNameStartIndex=String(tfsAppAdminUrl).indexOf("//")
    hostNameStopIndex=String(tfsAppAdminUrl).indexOf(":",hostNameStartIndex)
    hostName=String(tfsAppAdminUrl).substring(hostNameStartIndex+2,hostNameStopIndex)
    
    if (tfsAppTargetServer != (tfsAppDomainName+'.admin')): 
      '''SHUTDOWN Managed Servers'''

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

      nmConnect(tfsAppAdminUsername, tfsAppAdminPwd, hostName, nmPort, tfsAppDomainName,tfsAppDomainDir,tfsNmType)
      
      nmKill(tfsAppTargetServer) 
      nmStart(tfsAppTargetServer)    
    
      nmDisconnect();
    else: 
      '''SHUTDOWN and RESTART Admin Server, if Admin Server is the Target'''
      shutdown(tfsAppDomainName+'.admin','Server')
      startServer(tfsAppTargetServer, tfsAppDomainName, tfsAppAdminUrl, tfsAppAdminUsername, tfsAppAdminPwd, tfsAppDomainDir)
#end bounceWeblogic()
    
def deployTfsEnterpriseApp(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl):
    connect(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl)
    cd("AppDeployments")
    deploy(applicationName, applicationFilePath, tfsAppTargetServer, upload='true')
    startApplication(applicationName)
    disconnect()
#end deployTfsEnterpriseApp()

bounceWeblogic = sys.argv[1]
applicationName = sys.argv[2]
applicationFilePath = sys.argv[3]
tfsAppAdminUsername = sys.argv[4]
tfsAppAdminPwd = sys.argv[5]
tfsAppAdminUrl = sys.argv[6]
tfsAppTargetServer = sys.argv[7]
tfsAppDomainName = sys.argv[8]
tfsNodeMgrPort = sys.argv[9]
tfsAppDomainDir = sys.argv[10]
tfsNmType = sys.argv[11]

# undeploy any tfs EAR that is currently deployed.
undeployTfsEnterpriseApp(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl)

# bounce the server if requested
if(bounceWeblogic == 'True'):
    doBounceWeblogic(tfsAppAdminUrl, tfsAppDomainName, tfsNodeMgrPort, tfsAppAdminUsername, tfsAppAdminPwd, tfsAppTargetServer, tfsAppDomainDir, applicationName, applicationFilePath)

# deploy the tfs EAR to the target server.
deployTfsEnterpriseApp(tfsAppAdminUsername, tfsAppAdminPwd, tfsAppAdminUrl)

exit()
