#!/usr/bin/env python
import sys
import gobject
import bitfrost.update.actutils as actutils
import bitfrost.update.actinfo as actinfo
from sugar.bundle.contentbundle import ContentBundle

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
from sugar.activity.registry import get_registry
registry = get_registry()

def cmd_help():
    print 'Usage: sugar-install-bundle [ bundlename ] \n\n\
    Install an activity bundle (.xo). \n'

if len(sys.argv) != 2:
    cmd_help()
    sys.exit(2)

bundleHelper = actutils.BundleHelper(sys.argv[1])
if not bundleHelper.is_installed():
    bundleHelper.install_or_upgrade(registry)
    print "sugar-install-bundle: Installed new bundle '%s'" % (sys.argv[1])
else:
    if bundleHelper.is_activity:
        bundleVersion = bundleHelper.bundle.get_activity_version()
        installedVersion = registry.get_activity(bundleHelper.bundle.get_bundle_id()).version
    else:
        bundleVersion = bundleHelper.bundle.get_library_version()
        installedLibrary = ContentBundle(bundleHelper.bundle.get_root_dir())
        installedVersion = installedLibrary.get_library_version()
    if bundleVersion > installedVersion:
        bundleHelper.install_or_upgrade(registry)
        print "sugar-install-bundle: Upgraded bundle '%s' from version '%s' to '%s'" % \
            (sys.argv[1], installedVersion, bundleVersion)
    else:
        print "sugar-install-bundle: Bundle '%s' (version '%s') is not newer than " \
            "installed version '%s'" % (sys.argv[1], bundleVersion, installedVersion)
