#!/usr/bin/env bash

UTILPATH=${0%/*}

RUNNER="$1"
FILENAME="$2"
STARTSCRIPT="$3"
CLEANUPSCRIPT="$4"

TRIES=1

while ! grep -q 'CONTAINER_ID=' "$FILENAME" > /dev/null 2>/dev/null ; do
  sleep 1
  TRIES=$((1+$TRIES))
  if [ "$TRIES" -ge 20 ] ; then
    echo "$0: Containerfile $FILENAME did not show up after 20 seconds, giving up now!" >&2
    exit
  fi
done

sleep 1 # safety, we do not want to have half written container ids

CONTAINER_ID=`cat $FILENAME | grep 'CONTAINER_ID=' | sed 's/CONTAINER_ID=//'`

if echo "$CONTAINER_ID" | grep '\\n' > /dev/null ; then echo "Bad CONTAINER_ID (contains \\n), please check container file $FILENAME" ; fi

$STARTSCRIPT

while [ -e "$FILENAME" ] ; do
  sleep 1
  if ! $RUNNER ps --no-trunc | grep -q "$CONTAINER_ID" ; then
    #rm "$FILENAME"
    EXITED_FILENAME=`echo "$FILENAME" | sed 's/\([^\/]*\)$/.exited.\1/'`
    mv "$FILENAME" "$EXITED_FILENAME"
    exit
  fi
  inotifywait -e ATTRIB -t 10 "$FILENAME" > /dev/null 2>/dev/null
done

$RUNNER stop "$CONTAINER_ID" > /dev/null 2>/dev/null

$CLEANUPSCRIPT

#$UTILPATH/watchrun.sh "$FILENAME" "$STARTSCRIPT" "$CLEANUPSCRIPT"

