#!/bin/sh

#
# This file is part of tej
# https://github.com/VisTrails/tej
#
# Job starting wrapper
# Started on the server, detached, by the submit script
#
# Arguments:
#   1. command or script filename
#

set -e

(date; echo "start $@"; pwd) >> "$(dirname "$0")/../tej.log"

job_dir="$(pwd)"
script="$1"


# Starts program
if [ -f "./$script" ]; then
  chmod +x "./$script" 2>&1
  script="./$script"
fi
sh -c "$script" >_stdout 2>_stderr </dev/null &
pid=$!

# Writes status file
started_date=$(date +%s)
(echo "running"; echo $pid; echo "$started_date"; echo '') > ../status

wait $pid && exitcode=0 || exitcode=$?

(date; echo "finished $@"; echo $exitcode) >> "../../../tej.log"

# Updates status file
(echo "finished"; echo $exitcode; echo "$started_date"; date "+%s") > ../status

exit 0
