#! /usr/bin/env python

# Panflute
# Copyright (C) 2010 Paul Kuliniewicz <paul@kuliniewicz.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 2, 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 02111-1301, USA.

from __future__ import absolute_import

import panflute.daemon.manager
import panflute.util

import dbus.mainloop.glib
import gobject
import logging
import optparse
import os.path
import sys

if __name__ == "__main__":
    parser = optparse.OptionParser ()
    parser.add_option ("-s", "--silent",
                       action = "store_const", const = logging.CRITICAL + 1, dest = "log_level", 
                       help = "Log nothing")
    parser.add_option ("-v", "--verbose",
                       action = "store_const", const = logging.WARNING, dest = "log_level",
                       help = "Log all warnings and errors")
    parser.add_option ("-d", "--debug",
                       action = "store_const", const = logging.DEBUG, dest = "log_level",
                       help = "Log everything")
    parser.add_option ("-l", "--log-to-file",
                       action = "store_const", const = True, dest = "log_to_file",
                       help = "Log to file instead of stderr")

    options, args = parser.parse_args ()

    if options.log_level is None:
        options.log_level = logging.ERROR

    if options.log_to_file:
        dirname = panflute.util.get_xdg_data_home_directory ()
        stream = open (os.path.join (dirname, "daemon.log"), "w")
    else:
        stream = sys.stderr

    logging.basicConfig (stream = stream,
                         level = options.log_level,
                         format = "%(levelname)s [%(name)s] %(message)s")
    logger = logging.getLogger ("panflute")

    panflute.util.init_i18n ()
    dbus.mainloop.glib.DBusGMainLoop (set_as_default = True)
    gobject.threads_init ()

    manager = panflute.daemon.manager.Manager ()
    mainloop = gobject.MainLoop ()
    logger.debug ("Running panflute-daemon")
    mainloop.run ()
