#!/usr/bin/env python

import os
from subprocess import Popen, PIPE, call

import dbus
import gtk
from twisted.python.procutils import which

from wader.common.utils import save_file, get_file_data

from wader.bcm.consts import GTK_LOCK, APP_LONG_NAME
from wader.bcm.translate import _
from wader.bcm.splash import SplashScreen
from wader.bcm.startup import create_skeleton_and_return


def check_if_running():
    if not os.path.exists(GTK_LOCK):
        # if there's no lock we're cool
        return False

    cmd = "ps aux | grep 'python.*[b]cm' | awk '{ print $2 }'"
    pipe = Popen(cmd, shell=True, stdout=PIPE).stdout
    pid = pipe.read().strip()
    if not pid:
        return False

    saved_pid = get_file_data(GTK_LOCK).strip()
    if not saved_pid:
        # this shouldn't happen
        return False

    pids = pid.split('\n')
    if len(pids) > 1:
        # there's already a window running, plus us
        return True

    return int(pid) == int(saved_pid)


def raise_window():
    try:
        wmctrl_path = which('wmctrl')[0]
    except KeyError:
        raise RuntimeError("Cannot find wmctrl binary")
    else:
        call(["%s" % wmctrl_path, "-a", "%s" % APP_LONG_NAME])


def main():
    # check that uid != 0
    if not os.getuid():
        from wader.bcm.dialogs import show_error_dialog
        show_error_dialog(_("Do not run the application as root"),
                          _("Otherwise some features, like profiles, "
                            "might behave unpredictably."))
        return

    create_skeleton_and_return()

    # delay import until we have the necessary skeleton
    from wader.bcm.models.main import MainModel
    from wader.bcm.controllers.main import MainController
    from wader.bcm.views.main import MainView

    model = MainModel()
    ctrl = MainController(model)
    # XXX: :P
    model.ctrl = ctrl
    view = MainView(ctrl)

    # pass view to show after splash
    splash = SplashScreen(view)
    splash.show_it(1)

    # save the pid
    try:
        os.unlink(GTK_LOCK)
    except:
        pass

    save_file(GTK_LOCK, "%s" % str(os.getpid()))

    try:
        gtk.main()
    except KeyboardInterrupt:
        print "Removing gtk lock..."
        os.unlink(GTK_LOCK)


if __name__ == '__main__':
    if check_if_running():
        raise_window()
    else:
        main()
