
execfile('common.py')

connectToServer()

edit()
startEdit()

cd("/")

try:
  # Names are defined in common.py
  
  machine=cmo.lookupMachine(machineName)
  if machine is None:
    machine=cmo.createMachine(machineName)

  adminServer=cmo.lookupServer(adminName)
  if adminServer is not None:
    adminServer.setMachine(machine)
  
  dynamicServerTemplate=cmo.lookupServerTemplate(templateName)
  if dynamicServerTemplate is None:
    dynamicServerTemplate=cmo.createServerTemplate(clusterName+"-server-template")
  dynamicServerTemplate.setListenPort(8000)
  dynamicServerTemplate.setMachine(machine)
  
  #
  # Create the dynamic cluster and set the dynamic servers.
  #
  dynCluster=cmo.lookupCluster(clusterName)
  if dynCluster is None:
    dynCluster=cmo.createCluster(clusterName)
  
  dynServers=dynCluster.getDynamicServers()
  dynServers.setServerTemplate(dynamicServerTemplate)
  dynServers.setMinDynamicClusterSize(2)
  dynServers.setMaxDynamicClusterSize(8)
  dynServers.setDynamicClusterSize(4)
  dynServers.setDynamicClusterCooloffPeriodSeconds(120)
  dynServers.setCalculatedListenPorts(true)
  #dynServers.setCalculatedMachineNames(true)
  
  #
  # Dynamic server names will be dynamic-server-1, dynamic-server-2, ...,
  # dynamic-server-10.
  #
  dynServers.setServerNamePrefix(serverPrefix)
  
  save()
  activate()
  
  print "Undeploying existing web application"
  try:
    undeploy(appName='web', retireGracefully="false", block="true")
  except:
    print "Error undeploying, app likely not deployed"
    
  print "Deploying Simple webapp"
  deploy(appName='web',path="web.war",targets=clusterName, block="true", upload="true")

except:
  if editService.getConfigurationManager().isEditor():
    cancelEdit('y')
  raise
