#! /usr/bin/env python

# u1sdtool - command line utility for controlling ubuntuone-syncdaemon
#
# Author: Guillermo Gonzalez <guillermo.gonzalez@canonical.com>
#
# Copyright 2009 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/>.
from twisted.internet import glib2reactor
glib2reactor.install()

import dbus
import codecs
import os
import sys
import warnings

from dbus.mainloop.glib import DBusGMainLoop
from optparse import OptionParser
from twisted.internet import reactor, defer

from ubuntuone.syncdaemon.tools import SyncDaemonTool
from ubuntuone.syncdaemon.tools import (
    show_path_info,
    show_uploads,
    show_downloads,
    show_shares,
    show_shared,
    show_folders,
    show_error,
    show_state,
    show_waiting_content,
    show_waiting_metadata,
    show_public_file_info,
    is_running,
)


def main(options, args, stdout):
    """entry point"""
    loop = DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus(mainloop=loop)
    sync_daemon_tool = SyncDaemonTool(bus)

    # get the encoding of the output stream, defaults to UTF-8
    out_encoding = getattr(stdout, 'encoding', 'utf-8')
    if out_encoding is None:
        out_encoding = 'utf-8'
    out = codecs.getwriter(out_encoding)(stdout, errors='replace')
    # start syncdaemon if it's required
    if not is_running() and not options.quit and not options.start:
        d = sync_daemon_tool.start()
        d.addBoth(lambda _: run(options, sync_daemon_tool, out))
    else:
        d = run(options, sync_daemon_tool, out)

    def default_errback(error):
        """ default error handler. """
        out.write("\nOops, an error ocurred:\n")
        error.printTraceback()

    def stop_reactor(result):
        """ stop the reactor. """
        if reactor.running:
            reactor.stop()
    d.addErrback(default_errback)
    d.addCallback(stop_reactor)
    return d


def run(options, sync_daemon_tool, out):
    if options.wait:
        def callback(result):
            """ wait_for_nirvana callback (stop the reactor and exit)"""
            out.write("\nubuntuone-syncdaemon became a fully "
                      "enlightened Buddha!\n")

        d = sync_daemon_tool.wait_for_nirvana(verbose=True)
        d.addCallbacks(callback)
    elif options.list_shares:
        d = sync_daemon_tool.get_shares()
        d.addCallback(lambda r: show_shares(r, out))
    elif options.accept_share:
        d = sync_daemon_tool.accept_share(options.accept_share)
    elif options.reject_share:
        d = sync_daemon_tool.reject_share(options.reject_share)
    elif options.refresh_shares:
        d = sync_daemon_tool.refresh_shares()
    elif options.offer_share:
        path, username, name, access_level = options.offer_share
        d = sync_daemon_tool.offer_share(path, username, name, access_level)
    elif options.list_shared:
        d = sync_daemon_tool.list_shared()
        d.addCallback(lambda r: show_shared(r, out))
    elif options.create_folder:
        if not os.path.exists(options.create_folder):
            parser.error("PATH: '%s' don't exists" % \
                         options.create_folder)
        d = sync_daemon_tool.create_folder(options.create_folder)
        d.addErrback(lambda r: show_error(r, out))
    elif options.delete_folder:
        d = sync_daemon_tool.delete_folder(options.delete_folder)
        d.addErrback(lambda r: show_error(r, out))
    elif options.list_folders:
        d = sync_daemon_tool.get_folders()
        d.addCallback(lambda r: show_folders(r, out))
    elif options.subscribe_folder:
        d = sync_daemon_tool.subscribe_folder(options.subscribe_folder)
        d.addErrback(lambda r: show_error(r, out))
    elif options.unsubscribe_folder:
        d = sync_daemon_tool.unsubscribe_folder(options.unsubscribe_folder)
        d.addErrback(lambda r: show_error(r, out))
    elif options.publish_file:
        d = sync_daemon_tool.change_public_access(options.publish_file, True)
        d.addCallback(lambda info: show_public_file_info(info, out))
        d.addErrback(lambda failure: show_error(failure, out))
    elif options.unpublish_file:
        d = sync_daemon_tool.change_public_access(
                options.unpublish_file, False)
        d.addCallback(lambda info: show_public_file_info(info, out))
        d.addErrback(lambda failure: show_error(failure, out))
    elif options.refresh_path:
        if not os.path.exists(options.refresh_path):
            parser.error("PATH: '%s' don't exists" % \
                         options.refresh_path)
        d = sync_daemon_tool.query_by_path(options.refresh_path)
    elif options.path_info:
        if not os.path.exists(options.path_info):
            parser.error("PATH: '%s' don't exists" % \
                         options.path_info)
        d = sync_daemon_tool.get_metadata(options.path_info)
        d.addCallback(lambda r: show_path_info(r, options.path_info, out))
    elif options.current_transfers:
        d = sync_daemon_tool.get_current_uploads()
        d.addCallback(lambda r: show_uploads(r, out))
        d.addCallback(lambda _: sync_daemon_tool.get_current_downloads())
        d.addCallback(lambda r: show_downloads(r, out))
    elif options.quit:
        d = sync_daemon_tool.quit()
        def shutdown_check(result):
            if result is None and not is_running():
                out.write("ubuntuone-syncdaemon stopped.\n")
            else:
                out.write("ubuntuone-syncdaemon still running.\n")
        d.addBoth(shutdown_check)
    elif options.connect:
        d = sync_daemon_tool.connect()
    elif options.disconnect:
        d = sync_daemon_tool.disconnect()
    elif options.status:
        d = sync_daemon_tool.get_status()
        d.addCallback(lambda r: show_state(r, out))
    elif options.waiting_metadata:
        d = sync_daemon_tool.waiting_metadata()
        d.addCallback(lambda r: show_waiting_metadata(r, out))
    elif options.waiting_content:
        d = sync_daemon_tool.waiting_content()
        d.addCallback(lambda r: show_waiting_content(r, out))
    elif options.schedule_next:
        share_id, node_id = options.schedule_next
        d = sync_daemon_tool.schedule_next(share_id, node_id)
    elif options.start:
        d = sync_daemon_tool.start()
    else:
        parser.print_help()
        d = defer.succeed(None)
    return d


if __name__ == '__main__':
    # disable the dbus warnings
    warnings.filterwarnings('ignore', module='dbus')
    usage = "Usage: %prog [option]"
    parser = OptionParser(usage=usage)
    parser.add_option("-w", "--wait", dest="wait", action="store_true",
                      help="Wait until ubuntuone-syncdaemon reaches nirvana")
    parser.add_option("", "--accept-share", dest="accept_share",
                      metavar="SHARE_ID",
                      help="Accept the share with the specified id")
    parser.add_option("", "--reject-share", dest="reject_share",
                      metavar="SHARE_ID",
                      help="Reject the share with the specified id")
    parser.add_option("", "--list-shares", dest="list_shares",
                      action="store_true",
                      help="Get the list of shares")
    parser.add_option("", "--refresh-shares", dest="refresh_shares",
                      action="store_true",
                      help="Request a refresh of the list of shares to"
                      " the server")
    parser.add_option("", "--offer-share", dest="offer_share", type="string", 
                      nargs=4, metavar="PATH USER SHARE_NAME ACCESS_LEVEL",
                      help="Share PATH to USER. ")
    parser.add_option("", "--list-shared", dest="list_shared",
                      action="store_true",
                      help="List the shared path's/shares offered. ")
    parser.add_option("", "--create-folder", dest="create_folder",
                      metavar="PATH",
                      help="Create user defined folder in the specified path")
    parser.add_option("", "--delete-folder", dest="delete_folder",
                      metavar="FOLDER_ID",
                      help="Delete user defined folder in the specified path")
    parser.add_option("", "--list-folders", dest="list_folders",
                      action="store_true",
                      help="List all the user defined folders")
    parser.add_option("", "--subscribe-folder", dest="subscribe_folder",
                      metavar="FOLDER_ID",
                      help="Subscribe to the folder specified by id")
    parser.add_option("", "--unsubscribe-folder", dest="unsubscribe_folder",
                      metavar="FOLDER_ID",
                      help="Unsubscribe from the folder specified by id")
    parser.add_option("", "--publish-file", dest="publish_file",
                      metavar="PATH", help="Publish file publicly.")
    parser.add_option("", "--unpublish-file", dest="unpublish_file",
                      metavar="PATH", help="Stop publishing file publicly.")
    parser.add_option("", "--refresh", dest="refresh_path",
                      metavar="PATH", help="Request a refresh of PATH")
    parser.add_option("", "--info", dest="path_info",
                      metavar="PATH", help="Request the metadata of PATH")
    parser.add_option("", "--current-transfers", dest="current_transfers",
                      action="store_true",
                      help=" show the current uploads and downloads")
    parser.add_option("-q", "--quit", dest="quit", action='store_true',
                      help="Shutdown the syncdaemon")
    parser.add_option("-c", "--connect", dest="connect", action='store_true',
                      help="Connect the syncdaemon")
    parser.add_option("-d", "--disconnect", dest="disconnect", 
                      action='store_true', help="Disconnect the syncdaemon")
    parser.add_option("-s", "--status", dest="status", action='store_true', 
                      help="Get the current status of syncdaemon")
    parser.add_option("", "--waiting-content", dest="waiting_content", 
                      action='store_true', help="Get the waiting content list")
    parser.add_option("", "--waiting-metadata", dest="waiting_metadata", 
                      action='store_true', help="Get the waiting metadata list")
    parser.add_option("", "--schedule-next", dest="schedule_next", 
                      metavar="SHARE_ID NODE_ID", nargs=2, type='string',
                      help="Move the node to be the next in the queue of "
                      "waiting commands")
    parser.add_option("", "--start", dest="start", action='store_true', 
                      help="Start syncdaemon if it's not running")

    (options, args) = parser.parse_args(sys.argv)
    reactor.callWhenRunning(main, options, args, sys.stdout)
    reactor.run()

