#!/usr/bin/python2.5

# Copyright (C) 2007 INdT - Instituto Nokia de Tecnologia
# This file is part of Atabake
# Copyright (C) 2007 Instituto Nokia de Tecnologia . All rights reserved.
# Contact: Artur Duque de Souza <artur.souza@openbossa.org>
# This software, including documentation, is protected by copyright
# controlled by Instituto Nokia de Tecnologia. All rights are reserved.
# Copying, including reproducing, storing, adapting or translating, any
# or all of this material requires the prior written consent of
# Instituto Nokia de Tecnologia . This material also contains
# confidential information which may not be disclosed to others  without
# the prior written consent of Instituto Nokia de Tecnologia .

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

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()
