#!/usr/bin/env python

# This file is part of Atabake
# Copyright (C) 2007-2009 Instituto Nokia de Tecnologia
# Authors: Artur Duque de Souza <artur.souza@openbossa.org>
#
# 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.

__author__ = "Artur Duque de Souza / Leonardo Sobral Cunha"
__author_email__ = "artur.souza@openbossa.org / leonardo.cunha@openbossa.org"

import os
import sys
import logging

import atabake.lib.daemon
from atabake.lib.media_engine import MediaEngine
from atabake.lib.errors import DaemonStartError

import dbus
import dbus.service

from optparse import OptionParser

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


def start(log_file=None):
    try:
        daemon = MediaEngine(pidfile)
        if not daemon.start():
            sys.exit(1)
    except DaemonStartError, 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("Atabake is not running")
        sys.exit(1)

def restart(log_file=None):
    if not stop_daemon():
        log.error("Atabake is not running")
        sys.exit(1)

    start()

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):
        bus = dbus.SessionBus()
        try:
            me_obj = bus.get_object(MediaEngine.DBUS_SERVICE_NAME,
                                    MediaEngine.DBUS_OBJ_PATH,
                                    introspect=False)
        except Exception, e:
            return False
        me_iface = dbus.Interface(me_obj, MediaEngine.DBUS_IFACE)
        me_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 "
                  "Atabake's PID e.g.:/tmp/pidfile")
parser.add_option("-l", "--logfile", action="store",
                  dest="logfile", metavar="FILE",
                  help="Location of file to store "
                  "Atabake's LOGs e.g.:/tmp/atabake-log-file")


(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("atabake.loader")

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

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