#!/usr/bin/env python
#
# deluge
# Copyright (C) Zach Tibbitts 2006 <zach@collegegeek.org>
# Copyright (C) Alon Zakai    2006 <kripkensteiner@gmail.com>
# 
# 
#
# Deluge is free software.
# 
# You may 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.
# 
# deluge 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 deluge.  If not, write to:
#     The Free Software Foundation, Inc.,
#     51 Franklin Street, Fifth Floor
#     Boston, MA  02110-1301, USA.
#
#  In addition, as a special exception, the copyright holders give
#  permission to link the code of portions of this program with the OpenSSL
#  library.
#  You must obey the GNU General Public License in all respects for all of
#  the code used other than OpenSSL. If you modify file(s) with this
#  exception, you may extend this exception to your version of the file(s),
#  but you are not obligated to do so. If you do not wish to do so, delete
#  this exception statement from your version. If you delete this exception
#  statement from all source files in the program, then also delete it here.

import gettext
import locale
import os
import os.path
from optparse import OptionParser
import re
import sys

try:
    import dbus
    dbus_version = getattr(dbus, 'version', (0,0,0))
    if dbus_version >= (0,41,0) and dbus_version < (0,80,0):
        import dbus.glib
    elif dbus_version >= (0,80,0):
        from dbus.mainloop.glib import DBusGMainLoop
        DBusGMainLoop(set_as_default=True)
    else:
        pass
except: dbus_imported = False
else: dbus_imported = True

import deluge
import deluge.common
import deluge.core
import deluge.interface

parser = OptionParser(usage="%prog [options] [actions]", version=deluge.common.PROGRAM_VERSION)
parser.add_option("--tray", dest="tray", help="start Deluge hidden in system tray",
                        metavar="TRAY", action="store_true")

(options, args) = parser.parse_args()

def upgrade_old_persistent_state():
    pstate_file_path = os.path.join(deluge.common.CONFIG_DIR, 
                                    deluge.core.STATE_FILENAME)
    ## The persistent_state object moved from the deluge.deluge module to the
    ## deluge.core module from 0.5; so let's edit the user's saved data to 
    ## reflect this.
    if os.path.isfile(pstate_file_path):
        try:
            pstate_fd = open(pstate_file_path, "r")
            pstate_data = pstate_fd.read()
            pstate_fd.close()
            
            ## If the file was empty, then we should remove it so that the
            ## pickler doesn't not attempt to unpack an empty state.
            if len(pstate_data) is 0:
                os.remove(pstate_file_path)
                print "Empty persistent state data file removed successfully."
            ## The file exists and contains data, so let's do a regex-based
            ## find/replace to update the module name.
            else:
                pstate_old_regex = re.compile("\(ideluge\.deluge$", 
                                              re.MULTILINE)
                if re.search(pstate_old_regex, pstate_data):
                    pstate_new_data = re.sub(pstate_old_regex, 
                                             "(ideluge.core", pstate_data)
                    pstate_fd = open(pstate_file_path, "w")
                    pstate_fd.write(pstate_new_data)
                    pstate_fd.close()
                    print "Persistent state data updated successfully."
        except OSError, oopsie: 
            print >> sys.stderr, \
"""There was an error updating the persistent.state file.
If this is an upgrade from an earlier version of Deluge, this may cause bugs 
or failures in startup. You may wish to remove it manually. (%s)
Continuing...""" % pstate_file_path
            print >> sys.stderr, "The error was: %s." % oopsie

def get_cmd_line_torrents():
    cmd_line_torrents = []

    for torrent in args:
        if deluge.common.is_url(torrent):
            filename = deluge.common.fetch_url(torrent)
            if filename:
                cmd_line_torrents.append(filename)
        else:
            if not torrent.endswith(".torrent"):
                print "Error,", torrent, " does not seem to be a .torrent file"
            else:        
	            cmd_line_torrents.append(os.path.abspath(torrent))

    return cmd_line_torrents

def start_deluge():
    print "Starting new Deluge session..."

    upgrade_old_persistent_state()

    interface = deluge.interface.DelugeGTK()

    interface.start(options.tray, get_cmd_line_torrents())

if dbus_imported:
    bus = dbus.SessionBus()

    dbus_objects = dbus.Interface(bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus'), 'org.freedesktop.DBus').ListNames()

    interface = None

    if not "org.deluge_torrent.Deluge" in dbus_objects:
        print "no existing Deluge session"
        start_deluge()
    else:
        ## This connects to the deluge interface
        print "create proxy object"
        proxy = bus.get_object('org.deluge_torrent.Deluge', '/org/deluge_torrent/DelugeObject')
        print "create iface"
        deluge_iface = dbus.Interface(proxy, 'org.deluge_torrent.Deluge')
        print "send to iface"

        for filename in get_cmd_line_torrents():
            deluge_iface.interactive_add_torrent(filename)
else:
    print "no existing Deluge session"
    start_deluge()
