#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2009 Thomas Perl and the gPodder Team
#
# gPodder 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.
#
# gPodder 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/>.
#

"""
gPodder enables you to subscribe to RSS feeds and download
podcast episodes from these feeds. gPodder can operate in 
GUI mode and in CLI mode. Downloaded podcasts can either 
be synchronized to portable MP3 players (including iPods) 
or played back on the user's desktop.
"""

import sys
import os
import os.path
import platform

import gettext

try:
    import dbus
    import dbus.glib
    have_dbus = True
except ImportError:
    print >>sys.stderr, """
    Warning: python-dbus not found. Disabling D-Bus support.
    """
    have_dbus = False

from optparse import OptionParser

if __name__ == '__main__':
    # Paths to important files
    gpodder_script = sys.argv[0]
    if os.path.islink(gpodder_script):
        gpodder_script = os.readlink(gpodder_script)
    gpodder_dir = os.path.join(os.path.dirname(gpodder_script), '..')
    prefix = os.path.abspath(os.path.normpath(gpodder_dir))

    src_dir = os.path.join(prefix, 'src')
    data_dir = os.path.join(prefix, 'data')
    locale_dir = os.path.join(prefix, 'share', 'locale')
    ui_folder = os.path.join(prefix, 'share', 'gpodder', 'ui')
    icon_file = os.path.join(prefix, 'share', 'icons', 'hicolor', 'scalable', 'apps', 'gpodder.svg')

    if os.path.exists(src_dir) and os.path.exists(data_dir) and \
            not prefix.startswith('/usr'):
        # Run gPodder from local source folder (not installed)
        print >>sys.stderr, 'Using modules from', src_dir
        sys.path.insert(0, src_dir)
        print >>sys.stderr, 'Using resources from', data_dir
        locale_dir = os.path.join(data_dir, 'locale')
        ui_folder = os.path.join(data_dir, 'ui')
        icon_file = os.path.join(data_dir, 'gpodder.svg')

    # Set up the path to translation files
    gettext.bindtextdomain('gpodder', locale_dir)

    import gpodder

    # Enable i18n for gPodder translations
    _ = gpodder.gettext

    # Set up paths to folder with GtkBuilder files and gpodder.svg
    gpodder.ui_folder = ui_folder
    gpodder.icon_file = icon_file

    s_usage = 'usage: %%prog [options]\n\n%s' % ( __doc__.strip() )
    s_version = '%%prog %s' % ( gpodder.__version__ )

    parser = OptionParser( usage = s_usage, version = s_version)

    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose", default=False,
                      help=_("Print debugging output to stdout"))

    parser.add_option("-t", "--local",
                      action="store_true", dest="local", default=False,
                      help='Deprecated.')
    
    parser.add_option("-m", "--maemo",
                      action="store_true", dest="maemo", default=False,
                      help=_("Start the Maemo user interface of gPodder"))
    
    parser.add_option("-l", "--list",
                      action="store_true", dest="list", default=False,
                      help=_("List all channel subscriptions"))

    parser.add_option("-r", "--run",
                      action="store_true", dest="run", default=False,
                      help=_("Update channel list, download new podcasts"))

    parser.add_option("-u", "--update",
                      action="store_true", dest="update", default=False,
                      help=_("Update channel list and exit"))
    
    parser.add_option("-s", "--sync",
                      action="store_true", dest="sync", default=False,
                      help=_("Synchronize channels to configured device"))

    parser.add_option("-a", "--add", dest="add",
                      help=_("Subscribe to channel from URL"), metavar="URL")
    
    parser.add_option("-d", "--delete", dest="delete",
                      help=_("Delete channel specified by URL"), metavar="URL")

    parser.add_option("-S", "--stats",
			          action="store_true", dest="stats", default=False,
                      help=_("Get sync statistics"))

    (options, args) = parser.parse_args(sys.argv)

    if options.maemo:
        gpodder.interface = gpodder.MAEMO
    elif options.list or options.run or options.update or \
            options.sync or options.add or options.delete:
        gpodder.interface = gpodder.CLI
    else:
        gpodder.interface = gpodder.GUI

    if options.local:
        print >>sys.stderr, 'Ignoring deprecated option --local.'

    if options.verbose:
        from gpodder.liblogger import enable_verbose
        enable_verbose()

    if have_dbus:
        # Try to find an already-running instance of gPodder
        try:
            session_bus = dbus.SessionBus()
            remote_object = session_bus.get_object(gpodder.dbus_bus_name, gpodder.dbus_gui_object_path)
            from gpodder.liblogger import log
            log('Found gPodder GUI instance already running')
        except dbus.exceptions.DBusException:
            remote_object = None
    else:
        # No D-Bus available :/
        remote_object = None

    from gpodder import console
    if options.list:
        console.list_channels()
    elif options.run:
        console.run()
    elif options.update:
        console.update()
    elif options.sync:
        console.sync_device()
    elif options.add:
        console.add_channel( options.add)
    elif options.delete:
        console.del_channel( options.delete)
    elif options.stats:
        console.sync_stats()
    elif remote_object is not None:
        # An instance of GUI is already running
        remote_object.show_gui_window(dbus_interface=gpodder.dbus_interface)
    else:
        # gPodder is not yet running - create new instance
        from gpodder import gui

        # check if we have an X11 connection (but not on Windows)
        if platform.system() != 'Windows' and \
                not os.environ.get('DISPLAY', None):
            print >>sys.stderr, 'Cannot start gPodder: $DISPLAY is not set.'
            sys.exit(1)

        if gpodder.interface == gpodder.MAEMO:
            # Reduce our nice value to zero if we're on Maemo to
            # make the tablet not kill itself while updating feeds
            if os.nice(0) < 0:
                os.nice(-os.nice(0))

        gui.main()

