#!/usr/bin/env python

# Copyright (C) 2012 Science and Technology Facilities Council.
#
# 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 socket
import sys

import cherrypy
from cherrypy.lib.reprconf import Config

from crab.service.monitor import CrabMonitor
from crab.service.notify import CrabNotifyService
from crab.web.rss import CrabRSS
from crab.server import CrabServer
from crab.store.sqlite import CrabStoreSQLite
from crab.web.web import CrabWeb

def main():
    config = Config()
    config.update({'global': {'server.socket_port': 8000,
                              'server.socket_host': '0.0.0.0'},

                   'crab': {'home': os.path.join(sys.prefix, 'share', 'crab')},

                   'email': {'server': 'mailhost',
                             'from': 'Crab Daemon',
                             'subject_ok': 'Crab notification',
                             'subject_warning': 'Crab notification (WARNING)',
                             'subject_error': 'Crab notification (ERROR)'},

                   'notify': {'timezone': 'UTC',
                              'daily': '0 0 * * *'},

                   'store': {'type': 'sqlite',
                             'file': '/var/lib/crab/crab.db'}})

    env = os.environ

    if 'CRABSYSCONFIG' in env:
        sysconfdir = env['CRABSYSCONFIG']
    else:
        sysconfdir = '/etc/crab'

    try:
        config.update(os.path.join(sysconfdir, 'crabd.ini'))
    except IOError:
        pass

    try:
        config.update(os.path.expanduser('~/.crab/crabd.ini'))
    except IOError:
        pass

    if 'CRABHOME' in env:
        config['crab']['home'] = env['CRABHOME']

    config['/res'] = {'tools.staticdir.on': True,
                      'tools.staticdir.dir': config['crab']['home'] + '/res'}

    if config['store']['type'] == 'sqlite':
        store = CrabStoreSQLite(config['store']['file'])

    else:
        raise Exception('Unknown store type')

    base_url = ('http://' + socket.getfqdn() + ':' +
               str(config['global']['server.socket_port']))

    monitor = CrabMonitor(store)
    monitor.daemon = True
    monitor.start()

    notify = CrabNotifyService(config, store, base_url)
    notify.daemon = True
    notify.start()

    cherrypy.config.update(config)
    cherrypy.tree.mount(CrabWeb(config, store, monitor, {
                            'Monitor' : monitor,
                            'Notification' : notify
                        }), '/', config)
    cherrypy.tree.mount(CrabServer(store), '/api/0', {})
    cherrypy.tree.mount(CrabRSS(store, base_url), '/rss', {})

    cherrypy.engine.start()
    cherrypy.engine.block()

if __name__ == "__main__":
    main()
