# Function to get server state
def serverStatus(server):
  cd('/ServerLifeCycleRuntimes/' + server.getName() )
  return cmo.getState()
#
def startAdminserver():
  nmConnect(username, password, admindomain, 5100, domain, domain_dir)
  nmStart('AdminServer')
  nmDisconnect()
# End of functions
#
# Set some constants
username = 'weblogic'
password = 'weblogic123'
admindomain='DNS   app41.aac.DNS   '
domain = 'EEServiceDomain'

#
# Derived constants
url = 't3://' + admindomain + ':7100'
domain_dir =  os.environ['EEDOMAIN_HOME']  
nmhome =  os.environ['WL_HOME'] + r'/common/nodemanager'
nmpfile =  os.environ['WL_HOME'] + r'/common/nodemanager/nodemanager.properties'


#
# Connect to the AdminServer
try:
  connect(username, password,url)
except:
  # Aiks: AdminServer is not running. Start it now and retry
  startAdminserver()
  connect(username, password,url)
#
# Loop through the managed servers and start all servers running on localhost
svrs = cmo.getServers()
domainRuntime()
for server in svrs:
  # Do not start the adminserver, it's already running
  if server.getName() != 'AdminServer':
    # Get state and machine
    serverState = serverStatus(server)
    machine = server.getListenAddress()
    print server.getName() + " **** is " + serverState + " on " + machine
    #If not shutdown then shutdown the server
    if serverState != "SHUTDOWN":
      #if machine == localhost:
        shutdown(server.getName(),'Server')
        serverState = serverStatus(server)
        print "Now " + server.getName() + " is " + serverState + " on " + machine
    # startup if needed
    if serverState == "SHUTDOWN":
      #if machine == localhost:
        start(server.getName(),'Server')
        serverState = serverStatus(server)
        print "Now " + server.getName() + " is " + serverState + " on " + machine
         
disconnect()
exit()
