#!/bin/sh
_='''' # Prefer python3 if it exists
command -v python3 > /dev/null 2>&1 && exec python3 $0 "$@" || exec python $0 "$@"
'''

import sys
import os
try:
  import gtk as Gtk
  import glib as GLib
  import gio as Gio
  GtkVer = 2
except  Exception:
  import gi
  gi.require_version('Gtk', '3.0')
  from gi.repository import Gio, GLib, Gtk
  GtkVer = 3

MLoop = GLib.MainLoop()

def mount_done_cb(obj, res, data=0):
  try:
    obj.mount_enclosing_volume_finish(res)
  except Exception as err:
    print('Exception on mount: ' + err.message)
  finally:
    MLoop.quit()

if __name__ == '__main__':
  if len(sys.argv) != 2:
    print("Usage: bcmount <URI>");
    print("  <URI> must be a format supported by GVFS and the FUSE bridge");
    sys.exit(1)
  else:
    urib = None
    if GtkVer == 3:
      uri = Gio.File.new_for_uri(sys.argv[1])
    else:
      uri = Gio.File(uri=sys.argv[1])

    try:
      mnt = uri.find_enclosing_mount(None)
    except Exception:
      op = Gtk.MountOperation()
      if GtkVer == 3:
        uri.mount_enclosing_volume(Gio.MountMountFlags.NONE, op, None, mount_done_cb, None)
      else:
        uri.mount_enclosing_volume(op, mount_done_cb)
      MLoop.run()
      try:
        mnt = uri.find_enclosing_mount(None)
      except Exception:
        sys.exit(1)

    root = mnt.get_root()
    root_path = root.get_path()
    if root_path == None:
      tmp = os.popen("ps -C gvfsd-fuse").read()
      if 'gvfsd-fuse' not in tmp:
        print("gvfsd-fuse daemon not running")
      else:
        print("No local path")
      sys.exit(2)
    print(root_path)

    root_uri = root.get_uri()
    if root_uri == None:
      print("Unable to retrieve mount URL")
      sys.exit(1)
    print(root_uri)

    sys.exit(0)
