#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# When Wizard
#
# Copyright (c) 2015-2018 Francesco Garosi
# Released under the BSD License (see LICENSE file)
#
# Main application loader: setup global variables and run a specified script
# Usage: when-wizard script_name [arg1 .. argN]
#
# The code is kept as small as possible in order to be able to use this script
# also to load wrappers for operations that should be periodically run in the
# When applet, both to check conditions and to run tasks.

import os
import sys


#############################################################################
# constants

# base constants
APP_NAME = 'when-wizard'
APP_WHEN = 'when-command'
APP_FULLNAME = 'When Gnome Scheduler Wizard'
APP_SHORTNAME = 'When Wizard'
APP_COPYRIGHT = '(c) 2015-2016 Francesco Garosi'
APP_AUTHOR = 'Francesco Garosi'
APP_URL = 'http://almostearthling.github.io/when-command/'
APP_ID = 'it.jks.WhenWizard'
APP_LONGDESC = "A simple Wizard for easier setup of the When scheduler."

# NOTE: the following lines *must both* be edited at each release increment
# * the first holds the version ID that build utilities can extract
# * the second one includes a message that is used both as a commit message
#   and as a tag-associated message (in `git tag -m`)
APP_VERSION = '0.1.0~beta.4'
APP_TAGDESC = 'Remove GTK version warning on running plugin'


#############################################################################
# Support these installation schemes:
#
# * default: LSB standard (/usr/bin, /usr/share/when-wizard/*)
# * /opt based (/opt/when-wizard, /opt/when-wizard/share/when-wizard/*)
# * own folder ($FOLDER, $FOLDER/share/when-wizard/*)
#
# where first element is the invoked command directory, second one is the
# prefix of the app data folder (where dialogs, icons and other resources
# have to be installed); icons have their own subtree in the data folder;
# locales are either in standard system folders or a subtree of data folder.
APP_BASE_FOLDER = '/usr'
APP_BIN_FOLDER = os.path.join(APP_BASE_FOLDER, 'bin')
APP_DATA_FOLDER = os.path.join(APP_BASE_FOLDER, 'share', APP_NAME)
APP_LIB_FOLDER = os.path.join(APP_DATA_FOLDER, 'lib')
APP_GRAPHICS_FOLDER = os.path.join(APP_DATA_FOLDER, 'graphics')
APP_ICONS_FOLDER = os.path.join(APP_GRAPHICS_FOLDER, 'app-icons')
APP_RESOURCE_FOLDER = os.path.join(APP_DATA_FOLDER, 'ui')
APP_PLUGIN_FOLDER = os.path.join(APP_DATA_FOLDER, 'plugins')
APP_LOCALE_FOLDER = os.path.join(APP_BASE_FOLDER, 'share', 'locale')

INVOKED_CMD = os.path.realpath(sys.argv[0])
INVOKED_DIR = os.path.dirname(INVOKED_CMD)
if INVOKED_DIR == os.path.join('/opt', APP_NAME):
    APP_BIN_FOLDER = INVOKED_DIR
    APP_BASE_FOLDER = INVOKED_DIR
    APP_DATA_FOLDER = os.path.join(APP_BASE_FOLDER, 'share')
    APP_LIB_FOLDER = os.path.join(APP_DATA_FOLDER, 'lib')
    APP_RESOURCE_FOLDER = os.path.join(APP_DATA_FOLDER, 'ui')
    APP_PLUGIN_FOLDER = os.path.join(APP_DATA_FOLDER, 'plugins')
    APP_GRAPHICS_FOLDER = os.path.join(APP_DATA_FOLDER, 'graphics')
    APP_ICONS_FOLDER = os.path.join(APP_GRAPHICS_FOLDER, 'app-icons')
    APP_LOCALE_FOLDER = os.path.join(APP_DATA_FOLDER, 'locale')
elif not INVOKED_DIR.startswith('/usr'):
    APP_BIN_FOLDER = INVOKED_DIR
    APP_BASE_FOLDER = INVOKED_DIR
    APP_DATA_FOLDER = os.path.join(APP_BASE_FOLDER, 'share', APP_NAME)
    APP_LIB_FOLDER = os.path.join(APP_DATA_FOLDER, 'lib')
    APP_RESOURCE_FOLDER = os.path.join(APP_DATA_FOLDER, 'ui')
    APP_PLUGIN_FOLDER = os.path.join(APP_DATA_FOLDER, 'plugins')
    APP_GRAPHICS_FOLDER = os.path.join(APP_DATA_FOLDER, 'graphics')
    APP_ICONS_FOLDER = os.path.join(APP_GRAPHICS_FOLDER, 'app-icons')
    APP_LOCALE_FOLDER = os.path.join(APP_BASE_FOLDER, 'share', 'locale')

# configuration and store folders
USER_FOLDER = os.path.expanduser('~')
USER_DATA_FOLDER = os.path.join(USER_FOLDER, '.local', 'share', APP_WHEN)
USER_LAUNCHER_FOLDER = os.path.join(USER_FOLDER, '.local', 'share', 'applications')
USER_CONFIG_FOLDER = os.path.join(USER_FOLDER, '.config', APP_WHEN)
USER_STORE_FOLDER = os.path.join(USER_CONFIG_FOLDER, APP_NAME)
USER_PLUGIN_FOLDER = os.path.join(USER_DATA_FOLDER, APP_NAME, 'plugins')
USER_RESOURCE_FOLDER = os.path.join(USER_DATA_FOLDER, APP_NAME, 'resource')
USER_SCRIPT_FOLDER = os.path.join(USER_DATA_FOLDER, APP_NAME, 'scripts')

# if there is an environment variable defined as WHEN_WIZARD_DEVPLUGIN
# and it points to an existing path, then it is set as the plugin development
# folder, where all files related to a plugin can reside making it easier to
# develop a plugin before installation
try:
    PLUGIN_TEMP_FOLDER = os.environ['WHEN_WIZARD_DEVPLUGIN']
    if not os.path.isdir(PLUGIN_TEMP_FOLDER):
        PLUGIN_TEMP_FOLDER = None
except KeyError:
    PLUGIN_TEMP_FOLDER = None

# USER_CONFIG_FILE = os.path.join(USER_CONFIG_FOLDER, '%s.conf' % APP_NAME)
# USER_CONFIG = None


# the above pseudo-connstants should be available to all modules
__builtins__.APP_NAME = APP_NAME
__builtins__.APP_WHEN = APP_WHEN
__builtins__.APP_FULLNAME = APP_FULLNAME
__builtins__.APP_SHORTNAME = APP_SHORTNAME
__builtins__.APP_COPYRIGHT = APP_COPYRIGHT
__builtins__.APP_AUTHOR = APP_AUTHOR
__builtins__.APP_URL = APP_URL
__builtins__.APP_ID = APP_ID
__builtins__.APP_LONGDESC = APP_LONGDESC
__builtins__.APP_VERSION = APP_VERSION
__builtins__.APP_TAGDESC = APP_TAGDESC

__builtins__.APP_BIN_FOLDER = APP_BIN_FOLDER
__builtins__.APP_BASE_FOLDER = APP_BASE_FOLDER
__builtins__.APP_DATA_FOLDER = APP_DATA_FOLDER
__builtins__.APP_LIB_FOLDER = APP_LIB_FOLDER
__builtins__.APP_RESOURCE_FOLDER = APP_RESOURCE_FOLDER
__builtins__.APP_PLUGIN_FOLDER = APP_PLUGIN_FOLDER
__builtins__.APP_GRAPHICS_FOLDER = APP_GRAPHICS_FOLDER
__builtins__.APP_ICONS_FOLDER = APP_ICONS_FOLDER
__builtins__.APP_LOCALE_FOLDER = APP_LOCALE_FOLDER

__builtins__.USER_FOLDER = USER_FOLDER
__builtins__.USER_DATA_FOLDER = USER_DATA_FOLDER
__builtins__.USER_LAUNCHER_FOLDER = USER_LAUNCHER_FOLDER
__builtins__.USER_CONFIG_FOLDER = USER_CONFIG_FOLDER
__builtins__.USER_STORE_FOLDER = USER_STORE_FOLDER
__builtins__.USER_PLUGIN_FOLDER = USER_PLUGIN_FOLDER
__builtins__.USER_RESOURCE_FOLDER = USER_RESOURCE_FOLDER
__builtins__.USER_SCRIPT_FOLDER = USER_SCRIPT_FOLDER

__builtins__.PLUGIN_TEMP_FOLDER = PLUGIN_TEMP_FOLDER

__builtins__.APP_LOADER_SCRIPT = INVOKED_CMD
# __builtins__.USER_CONFIG_FILE = USER_CONFIG_FILE
# __builtins__.USER_CONFIG = USER_CONFIG


# update Python path
sys.path.insert(0, APP_DATA_FOLDER)
sys.path.insert(0, APP_LIB_FOLDER)

# import config
# USER_CONFIG = config.Config()


# the code below is used to load a script that has a main() function: this
# is required to avoid to give the script a reserved name; the particular
# form of the code allows the called application to be written as if it was
# directly run from the Python interpreter, except for having the main()
# entry point and for being aware of many already defined global variables
if __name__ == '__main__':
    if len(sys.argv) > 1:
        source_module = sys.argv[1]
        source_path = os.path.join(APP_DATA_FOLDER, source_module)
        if os.path.exists(source_path):
            from importlib.machinery import SourceFileLoader
            sys.argv = sys.argv[1:]
            module = SourceFileLoader(source_module, source_path).load_module()
            if hasattr(module, 'main'):
                ret = module.main()
                if ret:
                    try:
                        ret = int(ret)
                        sys.exit(ret)
                    except ValueError:
                        # generic error: exit code 2
                        sys.exit(2)
                else:
                    sys.exit(0)
            else:
                # cannot execute: exit code 126
                sys.exit(126)
        else:
            # command not found: exit code 127
            sys.exit(127)


# end.
