#!/usr/bin/python

# ubuntuone-start - Ubuntu One storage synchronization daemon startup helper
#
# Author: John Lenton <john.lenton@canonical.com>
#
# Copyright 2010 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.

import sys
import os

U1ROOT=os.path.expanduser('~/Ubuntu One/')

if __name__ == '__main__':
    # this check is done early to speed up startup on people who are not
    # (yet) using the service (this way avoids all the imports).
    if not os.path.isdir(U1ROOT):
        # no directory, just quit
        sys.exit(1)

import dbus
import glib
import gobject
import gnomekeyring
from dbus.mainloop.glib import DBusGMainLoop
from ubuntuone.syncdaemon.tools import SyncDaemonTool, is_running
from twisted.internet import defer

def stage_two(node, sync_daemon_tool):
    """do the last few checks and ask for a connect if all is ok"""
    d = None
    if node['node_id'] is not None:
        items = gnomekeyring.find_items_sync(
            gnomekeyring.ITEM_GENERIC_SECRET,
            {'ubuntuone-realm': 'https://ubuntuone.com'})
        if items:
            d = sync_daemon_tool.connect()
    if d is None:
        d = defer.fail(RuntimeError("bad node"))
    return d

def main():
    """Start syncdaemon and ask it to connect, if possible."""
    gobject.set_application_name("ubuntuone-launch")
    loop = DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus(mainloop=loop)
    sync_daemon_tool = SyncDaemonTool(bus)

    if not is_running():
        try:
            d = sync_daemon_tool.start()
        except dbus.exception.DBusException, e:
            d = defer.fail(e)
    else:
        d = defer.succeed(True)

    d.addCallback(lambda _: sync_daemon_tool.get_metadata(U1ROOT))
    d.addCallback(stage_two, sync_daemon_tool)
    # os._exit feels like it's cheating, but it's simple and fast
    d.addCallbacks(lambda _: os._exit(0), lambda _: os._exit(1))

    mainloop = glib.MainLoop()
    mainloop.run()

if __name__ == '__main__':
    main()
