#!/usr/bin/env python
"""
Generic application launcher.
"""

__author__ = 'Martin Blais <blais@furius.ca>'


import sys, re, os, platform
from os.path import join
from subprocess import call


ARG = object() # Constant used as a unique marker for the argument.

conf = os.environ.get('CONF', '')
combin = join(conf, 'bin')
defterm = "/usr/bin/gnome-terminal"

config = (

    ("debug", "ls -l"),

    ("xterm", "xterm -xrm ctwm.workspace:$currentworkspace -title CLIENTHOST -e bash"),
    ("rxvt", "urxvt"),
    ("(term|terminal|term-gnome)", "gnome-terminal"),
    ("bigterm", 'urxvt -fn "-*-lucidatypewriter-bold-*-*-*-*-240-*-*-*-*-*-*"'),

    ("emacs", "emacs"),

    ("netbuts", [defterm, '-e', "%s/bigbuts %s/network.bigbuts" % (combin, combin)]),

    ("lcdoff", "xset dpms force off"),
    ("single", "xrandr --output LVDS --mode 1280x800 --output TMDS-1 --off"),
    ("dual", "xrandr --output LVDS --mode 1280x800 --right-of TMDS-1 --output TMDS-1 --mode 1920x1200"),
    ("displayprop", "gnome-display-properties"),

    ('.*\.(jpg|jpeg|png|gif|bmp|xpm|xbm|ppm|pnm|xwd|tif|tiff)$', ['geeqie %s', 'gqview %s']),
    ('.*\.(svg)$', ['inkscape %s']),
    ('.*\.(html|htm)$', [os.environ['BROWSER'], '%s']),
    ('.*\.py$', ['python %s']),
    ('.*\.txt$', ['emacsclient -n %s']),
    ('.*\.(zip|tar|tar.gz|tar.bz2)$', ['atool --extract %s']),
    ('.*\.gz$', ['gunzip %s']),
    ('.*\.bz2$', ['bunzip2 %s']),
    ('.*\.pdf$', ['evince %s']), # acroread, xpdf
    ('.*\.chm$', ['xchm %s']), # acroread, xpdf
    ('.*\.djvu$', ['djview %s']),
    ('.*\.(doc|docx|rtf|odt|ods|pp[st])?$', ['libreoffice %s']), # abiword
    ('.*\.(mov|mp4|wmv|avi|ogv)$', ['vlc %s']),
    ('.*\.(wav|mp3|wma)$', ['mpg123 %s']),
    ('.*\.dia$', ['dia %s']),
    ('.*\.torrent$', ['bittorrent-curses %s']),
    ('.*\.(xls|gnumeric|csv)$', ['gnumeric %s']),
    ('.*\.(jar)$', ['java -jar %s']),
    ('.*\.(class)$', ['java %s']),

    ("monitor", [defterm, '-e', "yacpi"]),
    ("(suspend|sleep)", "sudo hibernate-ram"),
    ("syslog", '%s -e sudo tail -f /var/log/syslog' % defterm),

    )


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip())

    parser.add_option('-v', '--verbose', action='store_true',
                      help="Verbose output.")

    parser.add_option('-n', '--dry-run', action='store_true',
                      help="Output print command that would get run.")

    opts, args = parser.parse_args()

    if len(args) != 1:
        parser.error("You must specify some command or file to run.")
    arg = args[0]

    for matchstr, cmd in config:
        if re.match(matchstr, arg, re.I):
            if not isinstance(cmd, (tuple, list)):
                cmd = [cmd]
            for c in cmd:
                c = (c % ('"%s"' % arg)) if '%s' in c else c
                print c
                try:
                    r = call(c, shell=1)
                    if r != 0:
                        print >> sys.stderr, ("Error running '%s'" % c)
                        continue
                    break
                except OSError:
                    print >> sys.stderr, ("Error running '%s'" % c)
                except KeyboardInterrupt:
                    raise SystemExit("Interrupted.")
    else:
        print >> sys.stderr, "No suitable command for '%s'." % arg


if __name__ == '__main__':
    if platform.system() == 'Darwin':
        os.execv("/usr/bin/open", sys.argv)
    else:
        main()
