#!/usr/bin/python

# Copyright (C) 2014 Shinken Solutions
#
# This file is part of Shinken Enterprise, All rights reserved
#

import sys
import os
import imp
import ldap

if os.environ.get('SE-ENABLED') != '1':
    sys.exit(0)


print sys.modules
sys.modules['shinken'] = sys.modules['ldap']


from pprint import pprint


MOD_PATH = '/var/lib/shinken/modules'
modules_files = []
# Load directories
modules_files.extend([fname for fname in os.listdir(MOD_PATH) if os.path.isdir(os.path.join(MOD_PATH, fname))])

# Now we try to load them
# So first we add their dir into the sys.path
if not MOD_PATH in sys.path:
   sys.path.append(MOD_PATH)
print modules_files

for i in xrange(1, 25):
   print "LOOP", i
   for fname in modules_files:
       try:
          # Then we load the module.py inside this directory
          mod_file = os.path.abspath(os.path.join(MOD_PATH, fname,'module.py'))
          mod_dir  = os.path.dirname(mod_file)
          # We add this dir to sys.path so the module can load local files too
          sys.path.append(mod_dir)
          # important, equivalent to import fname from module.py
          m = imp.load_source(fname, mod_file)
          m_dir = os.path.abspath(os.path.dirname(m.__file__))
                
          # Look if it's a valid module
          if not hasattr(m, 'properties'):
	     print('Bad module file for %s : missing properties dict' % mod_file)
             continue
	    
          pprint(m.__dict__)
          print "LOADED", mod_file
          
                
       except ImportError, exp:
          print exp
          modname = exp.args[0].split(' ')[-1]
          other = ''
          if '.' in modname:
             modname = modname.split('.')[0]
             try:
                other = modname.split('.')[1]
             except IndexError:
                other = ''
          print "EMULATE MODULE", modname
          # We should not depends on shinken, so emulate it
          sys.modules['shinken.%s' % modname] = sys.modules['shinken']
          setattr(sys.modules['shinken.%s' % modname], modname, dict)
          setattr(sys.modules['shinken.%s' % modname], other, dict)


       except Exception, exp:
          # Oups, somethign went wrong here...
          print exp, dir(exp), type(exp)
          print("Importing module %s: %s" % (fname, exp))
