#!/usr/bin/env python

# Usage: run-it.py timeout file-to-watch maxkb cmd arg1 arg2 ...

import os, time, signal, sys
from sys import argv, stderr
from stat import *

timeout   = float(argv[1])
watchfile = argv[2]
maxsize   = float(argv[3])*1000
rest      = argv[4:]
cmd       = ' '.join(rest)
dt        = 0.1                         # polling interval
spawned   = os.times()[4]

# make this script the head of its own process group, in case we
# cannot do the same for the child
os.setpgrp()
child     = os.spawnvp(os.P_NOWAIT, rest[0], rest)
# now try to put the child as head of its own pgroup so that a killpg
# can catch grandchildren etc. (otherwise zillions of mktexnam
# processes stick around until their parent pdftex's are killed)
try:
    time.sleep(1)
    os.setpgid (child, 0)
    pg_tokill = child
except OSError, (errno, strerror):
    # probably the texexec child already did an exec
    print >>stderr, "%s: OSError[%d] in setpgid(%d): %s" % \
          (argv[0], errno, child, strerror)
    pg_tokill = os.getpgrp()            # better than nothing

while True:
    totalt = os.times()[4]-spawned
    if totalt > timeout:
        print >>stderr, "%s: Timeout %.1f sec reached [%s]" % (argv[0],
                                                               timeout, cmd)
        try:
            os.killpg(pg_tokill, signal.SIGINT)
        finally:           # in case of interrupt from the killpg
            sys.exit(5)
    bytes = os.stat(watchfile)[ST_SIZE]
    if bytes > maxsize:
        print >>stderr, "%s: Max size %d for %s reached [%s]" % (argv[0],
                                                                 maxsize,
                                                                 watchfile,
                                                                 cmd)
        try:
            os.killpg(pg_tokill, signal.SIGINT)
        finally:           # in case of interrupt from the killpg
            sys.exit(6)
    time.sleep(dt)
    (pid, status) = os.waitpid(child, os.WNOHANG)
    if status != 0:
        sys.exit('%s: "%s" finished with status %d' % (argv[0],cmd,status/256))
    if pid != 0:                        # child finished okay
        break
