#!/usr/bin/env python
import getopt
import logging
import os
import sys
import yaml

import aj
import aj.config
import aj.core
import aj.log
import aj.plugins


class ConfigFile(aj.config.BaseConfig):
    default_content = {
        'auth': {
            'allow_sudo': False,
            'provider': 'users',
            'users': {
                'root': {
                    # 'admin'
                    'password': '73637279707400100000000800000001f77e545afaeced51bdc33d16311ae24d900fbd462f444bce13d3c2aec489f90996523b8f779955a0f67708e0164de989c91a9a8093cd422fd5f5727018bb790f8aa36363273f5415660e7ff5c9fb9432e1f8ef5a3e35604ab9f2549aa85dbf2ca842573d25c02753bee5f0dd9c542b5ec51d58b443ad9f5e2b8dd9de8bd63a70908a1283c290bc7ccab30a3a88553ef23f5a6c25ccbe82e9f2b9ea656a6e373c33897e7b6376992de5cd00e78ed940486cd7bf0634ab1a1be2cf2f14ba2beabd55f82f5f3859ee9eea350c0a9fa9495749f0d0d6db21c5c17c742263e0e5bfb5c1c964edec1579c92ea538566151581bd06756564c21796eb61a0dd6d42b95ea5b1cdf667e0b06450622882fbf0bc7c9274903fd920368742769ee70e24a6d917afe6ba28faca235bcb83a1e22f37ee867d843b023424885623470940dd17c244a8f0ef998f29e5b680721d656c2a610609534e47ece10ea164b884d11ce983148aacf84044c5336bbc167fd28f45438',
                    'uid': 0
                }
            }
        },
        'bind': {
            'host': '0.0.0.0', 'mode': 'tcp', 'port': 8000
        },
        'max_sessions': 1,
        'name': 'Embedded System',
    }

    def __init__(self, path):
        aj.config.BaseConfig.__init__(self)
        self.data = None
        self.path = os.path.abspath(path)

    def __unicode__(self):
        return self.path

    def load(self):
        if not os.path.exists(self.path):
            self.data = self.default_content
        else:
            # harden permissions on the file
            if os.geteuid() == 0:
                os.chmod(self.path, 0600)
            self.data = yaml.load(open(self.path))

    def save(self):
        with open(self.path, 'w') as f:
            f.write(yaml.safe_dump(
                self.data,
                default_flow_style=False,
                encoding='utf-8',
                allow_unicode=True
            ))


def usage():
    print """
Usage: %s [options]
Options:
    -v                  - Debug/verbose logging
    -d, --daemon        - Run in background (daemon mode)
    -h, --help          - This help
    """ % sys.argv[0]


if __name__ == '__main__':
    log_level = logging.INFO
    daemonize = False
    debug_mode = False

    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'hdv',
            ['help', 'daemon']
        )
    except getopt.GetoptError as e:
        print str(e)
        usage()
        sys.exit(2)

    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif o in ('-v',):
            log_level = logging.DEBUG
            debug_mode = True
        elif o in ('-d', '--start'):
            daemonize = True

    aj.log.init_console(log_level)
    aj.core.start(
        config=ConfigFile('/etc/custom-web-ui.yml'),
        product_name='ajenti',
        daemonize=daemonize,
        debug_mode=debug_mode,
        # pick a suitable plugin provider
        plugin_providers=[
            #aj.plugins.PythonPathPluginProvider(),  # plugins installed with PIP
            aj.plugins.DirectoryPluginProvider('./plugins'),  # plugins from a directory
            aj.plugins.DirectoryPluginProvider('./plugins_custom'),  # plugins from a directory
        ],
    )
