#!/usr/bin/env python

# Copyright (C) 2012-2013 Aleksey Lim
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import locale
import logging
from os.path import exists, join

from gevent import monkey

import sugar_network_webui as webui
from sugar_network import db, node, client, toolkit
from sugar_network.db.router import Router
from sugar_network.node import stats_node, stats_user, obs
from sugar_network.node.master import MasterCommands
from sugar_network.node.slave import SlaveCommands
from sugar_network.resources.volume import Volume
from sugar_network.toolkit.http import Client
from sugar_network.toolkit import coroutine, application, util, Option, enforce


class Application(application.Daemon):

    jobs = coroutine.Pool()
    node = None

    def ensure_run(self):
        if toolkit.cachedir.value and not exists(toolkit.cachedir.value):
            os.makedirs(toolkit.cachedir.value)
        if not exists(node.data_root.value):
            os.makedirs(node.data_root.value)
        enforce(os.access(node.data_root.value, os.W_OK),
                'No write access to %r directory', node.data_root.value)

    def run(self):
        util.init_logging(application.debug.value)

        ssl_args = {}
        if node.keyfile.value:
            ssl_args['keyfile'] = node.keyfile.value
        if node.certfile.value:
            ssl_args['certfile'] = node.certfile.value

        volume = Volume(node.data_root.value)
        self.jobs.spawn(volume.populate)

        master_path = join(node.data_root.value, 'master')
        if exists(master_path):
            with file(master_path) as f:
                guid = f.read().strip()
            logging.info('Start %s node in master mode', guid)
            cp = MasterCommands(guid, volume)
        else:
            logging.info('Start slave node')
            cp = SlaveCommands(join(node.data_root.value, 'node.key'), volume)

        logging.info('Listening for requests on %s:%s',
                node.host.value, node.port.value)
        server = coroutine.WSGIServer((node.host.value, node.port.value),
                Router(cp), **ssl_args)
        self.jobs.spawn(server.serve_forever)
        self.accept()

        if webui.webui.value:
            # XXX Until implementing regular web users
            from sugar_network.client.commands import ClientCommands

            class _ClientCommands(ClientCommands):

                def call(self, request, response=None):
                    request.principal = 'demo'
                    return ClientCommands.call(self, request, response)

            client.sugar_uid = lambda: 'demo'
            # Point client API to volume directly
            client.mounts_root.value = None
            home_volume = Volume(join(application.rundir.value, 'db'))
            client_commands = _ClientCommands(home_volume,
                    api_url='http://localhost:%s' % node.port.value,
                    static_prefix=client.api_url.value)
            host = (node.host.value, webui.webui_port.value)
            logging.info('Start Web server on %s:%s port', *host)
            server = coroutine.WSGIServer(host,
                    webui.get_app(client_commands, client.api_url.value, True))
            self.jobs.spawn(server.serve_forever)

        try:
            self.jobs.join()
        finally:
            volume.close()

    def shutdown(self):
        self.jobs.kill()

    @application.command(
            'direct synchronization with master node',
            name='online-sync')
    def online_sync(self):
        self._ensure_instance().post(cmd='online-sync')

    @application.command(
            'sneakernet synchronization with other nodes using files '
            'placed to the specified directory',
            args='PATH', name='offline-sync')
    def offline_sync(self):
        enforce(self.args, 'PATH was not specified')
        path = self.args.pop(0)
        self._ensure_instance().post(cmd='offline-sync', path=path)

    def _ensure_instance(self):
        enforce(self.check_for_instance(), 'Node is not started')
        return Client('http://localhost:%s' % node.port.value, trust_env=False)


# Let toolkit.http work in concurrence
# XXX No DNS because `toolkit.network.res_init()` doesn't work otherwise
monkey.patch_socket(dns=False)
monkey.patch_select()
monkey.patch_ssl()
monkey.patch_time()

locale.setlocale(locale.LC_ALL, '')

Option.seek('main', application)
Option.seek('main', [toolkit.cachedir])
Option.seek('webui', webui)
Option.seek('client', [client.api_url])
Option.seek('node', node)
Option.seek('node-stats', stats_node)
Option.seek('user-stats', stats_user)
Option.seek('obs', obs)
Option.seek('db', db)

app = Application(
        name='sugar-network-node',
        description='Sugar Network node server',
        epilog='See http://wiki.sugarlabs.org/go/Sugar_Network '
               'for details.',
        config_files=[
            '/etc/sugar-network/config',
            '~/.config/sugar-network/config',
            ])
app.start()
