#!/usr/bin/env python

import sys

if __name__=="__main__":

  servertype = "local"
  server = None

  withgui = False

  for arg in sys.argv[1:]:
    arg = arg.lower()
    if arg == '--withgui':
      withgui = True
    else:
      servertype = arg
      break

#  if servertype not in ("cherry", "bottle", "thrift", "pyro", "local"):
#    print "USAGE: AutomatonServer [--withgui] [cherry|bottle|thrift|pyro|local]"
#    sys.exit()
    if servertype not in ("cherry", "local"):
      print "USAGE: AutomatonServer [--withgui] [cherry|local]"
    sys.exit()

  if servertype == "local" and not withgui:
    print "If local, must have GUI enabled."
    sys.exit()

  if servertype == "local":
    from automaton.server.base import AutomatonServer
    server = AutomatonServer(withgui=withgui)
    
  else:
    try:
      from automaton.server.cherry import CherryServer
      server = CherryServer(withgui=withgui)
      print "Using CherryPy"
    except ImportError as err:
      print "CherryPy failed to import - falling back to Thrift:", err
      servertype = "thrift"

  # Not elseif so that we can fallthrough if CherryPy fails
  if servertype == "thrift":
    try:
      from automaton.server.thrift import ThriftServer
      server = ThriftServer(withgui=withgui)
      print "Using thrift"
    except ImportError as err:
      print "Thrift failed to import - falling back to pyro:", err
      servertype = "pyro"

  if servertype == "pyro":
    try:
      from automaton.server.pyro import PyroServer
      server = PyroServer(withgui=withgui)
      print "Using Pyro"
    except ImportError:
      pass

  if server==None:
    print "Error: Specified server type not installed."
    sys.exit()

  # The local server has no initialization
  if hasattr(server, "initialize"):
    server.initialize()

  print 'Starting the server...'
  try:
    server.start()
  except KeyboardInterrupt:
    print "Keyboard Interrupt caught, exiting..."

