#!/usr/bin/python

import sys
import os

def silentfork(path, href, text, fetch):

    pid = os.fork()
    if not pid :
        # A lot of programs don't appreciate
        # having their fds closed, so instead
        # we dup them to /dev/null.

        fd = os.open("/dev/null", os.O_RDWR)
        os.dup2(fd, sys.stderr.fileno())

        if not text:
            os.setpgid(os.getpid(), os.getpid())
            os.dup2(fd, sys.stdout.fileno())

        if fetch:
            response = urllib2.urlopen(href)
            data = response.read()
            fd, name = tempfile.mkstemp()
            os.write(fd, data)
            os.close(fd)
            path = path.replace("%u", name)
        else:
            path = path.replace("%u", href)

        os.system(path)
        sys.exit(0)

    if text:
        signal.signal(signal.SIGALRM, signal.SIG_IGN)
        signal.signal(signal.SIGWINCH, signal.SIG_IGN)

    return pid

if __name__ == "__main__":
    silentfork("firefox \"%u\"", "http://codezen.org", 0, 0)    
