#########################################################################
""" 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

import _winghome

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

# Disable loading updates when running from sources or in remote agent install
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

#----------------------------------------------------------------------
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__))
  exec('import %s' % modname)
  sys.modules.pop(modname, None)

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

#-----------------------------------------------------------------------
if __name__ == '__main__':

  # Find winghome and user settings directory and put into the _winghome module
  winghome = os.path.dirname(os.path.dirname(os.path.normpath(__file__)))
  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
  startremoteagent.RunRemoteAgent()

