import commands, re, os, threading, time, sys 

WAIT_TIME = 15

class monitor_thread(threading.Thread):
        def __init__(self):
                self.pulse()
                threading.Thread.__init__ (self)

        def run(self):
                while time.time() - self.lasttime < WAIT_TIME:
                        time.sleep(1)
                if self.lasttime > 0:
                        print "dropboxd ran for %u seconds without quitting - success?" % WAIT_TIME
                commands.getstatusoutput("killall dropboxd")

        def pulse(self):
                self.lasttime = time.time()

        def stop(self):
                self.lasttime = 0

mon = monitor_thread()
mon.start()

try:
        r_undef = re.compile('ImportError: /.*/.dropbox-dist/(.*?): undefined symbol: (.*)')
        r_noso = re.compile('ImportError: (.*): cannot open shared object file: No such file or directory')
        ok = True
        errmsg = ""
        dropboxd = os.path.expanduser("~/.dropbox-dist/dropboxd")

        def compile_fakelib():
                ret = commands.getstatusoutput("gcc -fPIC -shared -o ~/.dropbox-dist/fakelib fakelib.c")
                if ret[0] != 0:
                        raise Exception, ret[1]

        commands.getstatusoutput('echo "#define E(f) int f() {return 0;}" > fakelib.c')
        compile_fakelib()

        while ok:
                ok = False
                mon.pulse()
                errmsg = commands.getoutput(dropboxd)

                found = r_noso.findall(errmsg.split("\n")[-1])
                if found != []:
                        print "adding library " + found[0]
                        commands.getstatusoutput("ln -s fakelib ~/.dropbox-dist/" + found[0])
                        ok = True

                found = r_undef.findall(errmsg.split("\n")[-1])
                if found != []:
                        print "adding function "+ found[0][1]
                        ret = commands.getstatusoutput('echo "E(' + found[0][1] + ')" >> fakelib.c')
                        compile_fakelib()
                        ok = True
except:
        mon.stop()
        raise

print errmsg
mon.stop()

