#!/usr/bin/env python
# coding=UTF-8

__author__ = "Pierre-Yves Langlois"
__copyright__ = "https://github.com/pylanglois/uadm/blob/master/LICENCE"
__credits__ = ["Pierre-Yves Langlois"]
__license__ = "BSD"
__version__ = "1.0"
__maintainer__ = "Pierre-Yves Langlois"
__status__ = "Production"

"""
This is an example script using the uadm scripting tools
"""

import sys
import os
import imp

from uadm.uadmcore import *

def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

if __name__ == "__main__":

    try:
        if len(sys.argv) >= 2:
            command = sys.argv[1].replace("/","").strip(".")
            import_path = "%s/%s" % (CONF_MAP["UADM_SCRIPT_PATH"], command)
            import_path_py = "%s.py" % import_path

            if (os.path.exists(import_path) and is_exe(import_path)) or \
               (os.path.exists(import_path_py) and is_exe(import_path_py)):

                import_path = import_path if os.path.exists(import_path) else import_path_py
                script_mod = imp.load_source("*", import_path)
                mod_conf({"UADM_TOOL_NAME": command})
                l(init_logger())
                script_mod.run(sys.argv[1:])
            
            else:
                l().error("Command '%s' does not exists or is not executable." % import_path)
                exit(1)
        else:
            l().error("You need to specify a script name from /etc/uadm/scripts/xxx with params if needed")
            exit(1)
    except:
        l().exception("Something went wrong!!!")
        exit(1)

