#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH

(if (< (length *arguments*) 3)
  (print-format *standard-error* 
    "USAGE: timeout N commands...
launches the shell commands with a timeout of N seconds in parallel
returns 0 if process terminated, and 1 if were timeouted
"))

(setq return-code 0)

;; launch the commands and a timeout process
(setq timeout-pid (system (list "sleep" (get *arguments* 1))))
(setq command-pid (list))
(setq command-names (list))
(dolist (command (subseq *arguments* 2))
  (put command-pid -1 (setq pid (system command)))
  (put command-names pid command)
)

(wait (+ (list timeout-pid) command-pid) :blocking 1)

;; then kill everybody

(insert command-pid -1 timeout-pid)

;; kill gently
(dolist (pid command-pid)
  (if (not (wait pid :blocking ()))	; still alive?
    (progn
      (if (/= pid timeout-pid) (progn
	  (print-format () "Timeouting process: %0\n"
	    (get command-names pid "???")
	  )
	  (setq return-code 1)
	)
      )
      (system (list "kill" (String  pid)) :error 'dummy)
    )
))

;; then kill forcibly after 1s
(wait (system "sleep 1"))
(dolist (pid command-pid)
  (if (not (wait pid :blocking ()))	; still alive?
    (system (list "kill" "-9" (String pid)) :error 'dummy)
))

(print-format () "Returning %0\n" return-code)
(exit return-code)
