#!/usr/bin/env python

# Copyright (C) 2005-2007 INdT - Instituto Nokia de Tecnologia
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

__author__ = "Artur Duque de Souza"
__author_email__ = "artur.souza@openbossa.org"
__license__ = "GPL"
__version__ = "0.1.1"

import os
import sys
import stat
import dbus
import logging

from canolad.daemon import Daemon
from optparse import OptionParser

log_level = logging.INFO
pidfile = "/tmp/canolad-%d.pid" % os.getuid()
logfile = os.devnull

def start():
    try:
        daemon = Daemon(pidfile)
        if not daemon.start():
            sys.exit(1)
    except LookupError, e:
        log.error(e)
        sys.exit(1)
    except Exception, e:
        if os.path.exists(pidfile):
            os.remove(pidfile)
        log.error(e, exc_info=True)
        sys.exit(1)

def stop():
    if not stop_daemon():
        log.error("Canola Daemon is not running")
        sys.exit(1)

def restart():
    if not stop_daemon():
        log.error("Canola Daemon is not running")
        sys.exit(1)
    try:
        daemon = Daemon(pidfile)
        if not daemon.start():
            sys.exit(1)
    except Exception, e:
        if os.path.exists(pidfile):
            os.remove(pidfile)
        log.error(e, exc_info=True)
        sys.exit(1)

def stop_daemon():
    # We are not the daemon and because of this we need to stop it
    # using dbus, just like a client would do
    if os.path.exists(pidfile):
        log.info("Trying to stop daemon. It may take a while")
        bus = dbus.SessionBus()
        obj = bus.get_object(Daemon.DBUS_SERVICE_NAME,
                             Daemon.DBUS_OBJ_PATH,
                             introspect=False)
        iface = dbus.Interface(obj, Daemon.DBUS_IFACE)
        iface.stop()
        return True
    return False


usage = "Usage: %prog [options] start | stop | restart"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", dest="verbosity", action="count",
                  help="Use this option to increase verbosity")
parser.add_option("-p", "--pidfile", action="store",
                  dest="pidfile", metavar="FILE",
                  help="Location of file to store "
                  "canolad's PID e.g.:/tmp/pidfile")
parser.add_option("-l", "--logfile", action="store",
                  dest="logfile", metavar="FILE",
                  help="Location of file to store "
                  "canolad's logfile e.g.:/tmp/logfile")

(options, args) = parser.parse_args()

if len(args) != 1:
    parser.error("You need to specify at least one action")
    sys.exit(2)

if options.verbosity:
    log_level -= 10 * options.verbosity

if options.pidfile:
    pidfile = options.pidfile

if options.logfile:
    logfile = options.logfile

logging.basicConfig(filename=logfile, level=log_level,
                    format=("== %(asctime)s %(name)-18s =="
                            "\t%(levelname)-8s \t%(message)s"),
                    datefmt="%Y-%m-%d %H:%M:%S")
log = logging.getLogger("canola.daemon")

commands = {
    "start": start,
    "stop": stop,
    "restart": restart
    }

engine_cmd = commands[args[0]]
engine_cmd()
