#!/usr/bin/env python

#************************************************************************/
#* wbumount-gtk                                                         */
#*                                                                      */
#* Copyright (c) 2004 by Norbert Frese                                  */
#*                                                                      */
#* This program is free software. You can 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.       */
#************************************************************************/


import pygtk
pygtk.require("2.0")
import gtk
import gobject
import re
import os
import sys
import commands

VERSION = "0.1.4"

ICON_PATH= "/usr/share/pixmaps/wbumount.png"

view = None

currMountPoint=None

#mountpCombo = None
mpMenuItem = None
listMps = None


myWindow=None
myListModel=None
umountButton=None
ejectButton=None

statusLabel = None

#
#  show text in status label
#
def show_status(message):
    global statusLabel
    statusLabel.set_label(message)

#
#  quit application
#
def quit(*args):
    gtk.main_quit()

#
#  create list-view
#
def make_view(model):
    # Create the view itself.
    view = gtk.TreeView(model)
    renderer = gtk.CellRendererText()
    column = gtk.TreeViewColumn("Process", renderer, text=1)
    view.append_column(column)
    view.show()

    # Create scrollbars around the view.
    scrolled = gtk.ScrolledWindow()
    scrolled.add(view)
    scrolled.show()

    return view, scrolled

#
#  change current mountpoint
#
def select_mountpoint(obj, mountPoint):
    global currMountPoint
    print "selected: " + mountPoint
    currMountPoint=mountPoint
    updateListModel()

#
#  get list of mountpoints belonging to current user
#
def list_mountpoints():
    
    splitRegex = re.compile(r'\s+')

    listMps = []

    fd = open("/etc/mtab")
    

    lines = fd.readlines();
    for line in lines:
        # print line
        spl= splitRegex.split(line)
	if len(spl) > 4 :
		devCol = spl[0]
		mpCol = spl[1]
		typeCol = spl[2]
		optCol = spl[3]
		# dirty hack: doesnt check which user
                if not re.match(".*user=.*", optCol):
			continue;

                listMps.append(mpCol)
    fd.close()
    return listMps

#
#  get list of processes on mountpoint
#
def wbumount_list(mountpoint):
	
    listComm = []

    print ">>> wbumount mountpoint " + str(mountpoint) + ":"

    # ---- Run 'wbumount'

    # cmdpipe = os.popen('wbumount ' + mountpoint, 'r');
    # lines = cmdpipe.readlines();

    (rval, outp) = commands.getstatusoutput('wbumount ' + mountpoint + ' 2>/dev/null')

    # ---- Extract lines

    splitRegex = re.compile(r'\n')

    lines = splitRegex.split(outp)

    #fd = open("/tmp/testlala2","w")
    #fd.write(outp)
    #fd.close


    # resp = cmdpipe.read();
    # print resp;

    # ---- Extract columns

    splitRegex = re.compile(r'\s+')

    
    for line in lines:
	
	print line;
	
	spl= splitRegex.split(line)
	print spl

	if len(spl) >= 5 :
		mpointCol = spl[0]
		userCol = spl[1]
		pidCol = spl[2]
		typeCol = spl[3]
		commandCol = spl[4]

		if userCol == "USER" and pidCol == "PID": continue		
		if pidCol == "kernel" and typeCol == "mount" : continue

		if commandCol == "fam": 
			dispText = "fam (Nautilus, Konqueror Filemanager,...)"
		else:
			dispText = commandCol

		listComm.append(dispText)

    # rval = cmdpipe.close()
    print "WBUMOUNT Errorcode: " + str(rval)
    
    if rval != 0:
	if rval == 512:
		show_status("you are not the owner of: '" + str(mountpoint) + "' !")
        else:
		if rval == 256:
			show_status("'" + str(mountpoint) + "' not mounted!")
		else:
    			show_status("wbumount Errorcode:" + str(rval))
    else:
        show_status("monitoring mountpoint: " + str(mountpoint))

    global myWindow
    myWindow.set_title("wbumount [" + str(mountpoint) + "]")

    print listComm
    return listComm

#
#  list processes on current mountpoint
#
def updateListModel():
    global myListModel
    global currMountPoint
    global umountButton
    global ejectButton


    myListModel.clear()

    if (currMountPoint == None):
        umountButton.set_sensitive(0)
	ejectButton.set_sensitive(0)
        show_status("no mountpoint selected!")        
	return 

    listComm = wbumount_list(currMountPoint)
    for comm in listComm:
	iter = myListModel.insert_before(None, None)
       	myListModel.set_value(iter, 0, 0)
       	myListModel.set_value(iter, 1, comm)

    # ---- grey out or not grey out buttons
    if len(listComm) == 0 :
	umountButton.set_sensitive(1)
        ejectButton.set_sensitive(1)
    else:
	umountButton.set_sensitive(0)
	ejectButton.set_sensitive(0)

#
#  compare python lists
#
def compare_lists(list1, list2):
    if list1 == None and list2 == None: return 1
    if list1 == None or list2 == None: return 0

    if len(list1) != len(list2): return 0
    for i in range(len(list1)):
        a = list1[i]
        b = list2[i]
        if (a != b):
            return 0
    return 1

#
#  update menu of mountpoints which belong to current user
#
def update_mountpoint_menu():

    #global mountpCombo
    global mpMenuItem
    global listMps
    global currMountPoint

    newListMps = list_mountpoints();

    # ---- Update necessary?
    if compare_lists(listMps, newListMps): return
    listMps = newListMps

    # ---- Create new Menu
    menu = gtk.Menu()    
    
    #if len(listMps)>0 and currMountPoint == None:
    #    currMountPoint=listMps[0]

    for mp in listMps:
        	
        menu_items = gtk.MenuItem(mp)
	
        menu.append(menu_items)
	
        menu_items.connect("activate", select_mountpoint, mp)

        menu_items.show()

    menu.show()
    #mountpCombo.set_menu(menu)
    mpMenuItem.set_submenu(menu)

#
#  gets called every second
#
def update_timer(*args):

    update_mountpoint_menu()
    updateListModel()

    return 1

#
#  eject mountpoint
#
def eject(*args):
    global currMountPoint
    cmdpipe = os.popen('eject ' + currMountPoint, 'r');

#
#  umount mountpoint
#
def umount(*args):
    global currMountPoint
    cmdpipe = os.popen('umount ' + currMountPoint, 'r');

#
#  show about box
#
def show_about_box(*args):
    global myWindow
    global VERSION
    print "show about"
    aboutStr = "wbumount-gtk " + VERSION + "\n\nWho is blocking umount?\n\n(c) 2004 Norbert Frese"
    aboutBox =gtk.MessageDialog(parent=myWindow, flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, message_format=aboutStr)
    aboutBox.set_default_response(gtk.BUTTONS_OK)
    aboutBox.run()
    aboutBox.destroy()

#
#  application body
#
def main():
    global myListModel
    global currMountPoint
    global myWindow
    #global mountpCombo
    global mpMenuItem
    global umountButton
    global ejectButton

    # ---- parse command-line arguments

    currMountPoint = None

    if len(sys.argv) > 1:
        currMountPoint = sys.argv[1]
        print "monitoring: " + str(currMountPoint)

    # ---- Create the model.
    model = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING)

    myListModel = model

    
    

    # ---- Create the main view.
    global view
    view, scrolled = make_view(model)
    view.set_reorderable(gtk.TRUE)

    # ---- Create Menu
    menuBar= gtk.MenuBar()
    #rootMenu = gtk.Menu()
   
    # ----- File Menu

    quitMenuItem = gtk.MenuItem("Quit")
	
    quitMenuItem.connect("activate", quit, None)
    quitMenuItem.show()

    fileMenuItem = gtk.MenuItem("File")
    fileMenuItem.show()

    fileMenu = gtk.Menu()    
    fileMenu.append(quitMenuItem)
    fileMenu.show() 

    fileMenuItem.set_submenu(fileMenu)

    # ----- MP Menu
    mpMenuItem = gtk.MenuItem("Mountpoint")
    mpMenuItem.show()

    # ----- About Menu
    aboutMenuItem = gtk.MenuItem("About...")
	
    aboutMenuItem.connect("activate", show_about_box, None)
    aboutMenuItem.show()

    helpMenuItem = gtk.MenuItem("Help")
    helpMenuItem.show()

    helpMenu = gtk.Menu()    
    helpMenu.append(aboutMenuItem)
    helpMenu.show()

    helpMenuItem.set_submenu(helpMenu)
    #rootMenu.show()

    # ----- Fill Menu bar
    menuBar.append(fileMenuItem)    
    menuBar.append(mpMenuItem)
    menuBar.append(helpMenuItem)
    menuBar.show()

    # ---- Create mountpoint menu



#    mountpCombo = gtk.Combo()
    #mountpCombo = gtk.OptionMenu()

    #mountpCombo.set_popdown_strings(slist)
    #mountpCombo.show()


    # ---- Create buttons.

    buttonbox = gtk.HBox()
    cancelButton = gtk.Button(stock=gtk.STOCK_CANCEL)
    #cancelButton.set_label("Cancel")
    cancelButton.connect("clicked", quit)
    cancelButton.show()
    buttonbox.pack_start(cancelButton, expand=gtk.FALSE, fill=gtk.FALSE)

    umountButton = gtk.Button()
    umountButton.set_label("  ^ Umount  ")
    umountButton.connect("clicked", umount)
    umountButton.show()
    buttonbox.pack_start(umountButton, expand=gtk.FALSE, fill=gtk.FALSE)

    ejectButton = gtk.Button()
    ejectButton.set_label("  ^ Eject  ")
    ejectButton.connect("clicked", eject)
    ejectButton.show()

    buttonbox.pack_start(ejectButton, expand=gtk.FALSE, fill=gtk.FALSE)
    buttonbox.show()

    # ---- Create Statuslabel
    
    global statusLabel
    statusLabel = gtk.Label("wbumount")
    statusLabel.show()

    # ---- Create a vertical box to hold the above stuff.
    vbox = gtk.VBox(spacing=5)
    
    vbox.pack_start(menuBar, expand=gtk.FALSE, fill=gtk.FALSE)
    vbox.pack_start(scrolled, expand=gtk.TRUE, fill=gtk.TRUE)
    vbox.pack_start(statusLabel, expand=gtk.FALSE, fill=gtk.FALSE)
    vbox.pack_start(buttonbox, expand=gtk.FALSE, fill=gtk.FALSE)

    vbox.show()

    # ---- Set icon

    
    if os.path.exists(ICON_PATH):
            pixbuf = gtk.gdk.pixbuf_new_from_file(ICON_PATH)
            gtk.window_set_default_icon_list((pixbuf))
    else:
            print "icon wbumount not found!"


    # ---- Create toplevel window to show it all.
    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.connect("delete_event", quit)
    win.add(vbox)
    win.set_title("wbumount")
    win.show()
    win.resize(300, 300)

    myWindow = win
    
    # ---- Update and draw list of processes on current mp.
    updateListModel()
    gtk.timeout_add(1000, update_timer)

    
    # ---- Run the Gtk+ main loop.
    gtk.main()
    
if __name__ == "__main__":
    main()
