#########################################################################
""" remoteagent.py    -- Remote agent for Wing
                    
Copyright (c) 2015-2018, Archaeopteryx Software, Inc.  All rights reserved.

Written by Stephan R.A. Deibel and John P. Ehresman

"""
#########################################################################

# This is the non-patchable remote agent startup module

import sys
import os
import traceback
import time


# Set __file__ if not already set
try:
  __file__
except NameError:
  __file__ = sys.argv[0]

# Disable loading updates when running from sources:  The import may
# fail if running without current directory in sys.path; in that case
# updates are always loaded
try:
  import _winghome
  indicator_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                                'src', 'debug', 'tserver', 'tracercore.c')
  if os.path.exists(indicator_file):
    _winghome.kLoadUpdates = False
  else:
    _winghome.kLoadUpdates = True
except ImportError:
  pass

#----------------------------------------------------------------------
def NP_LoadModuleHere(modname):
  """Load the given module from same directory as this file
  without adding it to sys.modules"""

  sys.modules.pop(modname, None)

  sys.path.insert(0, os.path.dirname(__file__))
  mod = __import__(modname)
  sys.modules.pop(modname, None)

  sys.path = sys.path[1:]
  return mod
  
bootstrap_utils = NP_LoadModuleHere('bootstrap_utils')

#-----------------------------------------------------------------------
if __name__ == '__main__':
  
  try:
    
    # Find winghome and user settings directory and put into the _winghome module
    absname = os.path.abspath(os.path.normpath(__file__))
    winghome = os.path.dirname(os.path.dirname(absname))
    winghome, user_settings = bootstrap_utils.NP_SetupWingHomeModule(winghome)
  
    # Set up the meta importer so remote agent is updateable
    meta = bootstrap_utils.NP_CreateMetaImporter(winghome, user_settings, 'dbg',
                                                 logger=sys.stdout)
  
    # Start the remote agent; everything below here can be updated
    from debug.tserver import startremoteagent
    print('REMOTE AGENT STARTING')
    startremoteagent.RunRemoteAgent()

  except:
    print('REMOTE AGENT FAILED TO START')
    traceback.print_exc()
    
  