#!/bin/sh

#
# This file is part of tej
# https://github.com/remram44/tej
#
# Job status script
# Started on the server to get the status of a job
#
# Arguments:
#   1. job ID
#
# Returns:
#   0 if job is done, 2 if job is still running, 3 if there is no such job
#   (already removed?)
#   If "0", prints exit code on stdout
#

# Inputs
job_id="$1"

cd "$(dirname $0)/.."

(date; echo "status $@") >> tej.log

job_root="jobs/$job_id"

if ! [ -d "$job_root" ]; then
    echo "No job '$job_id'" >&2
    echo "No such job" >> tej.log
    exit 3
fi

if [ -f "$job_root/status" ]; then
    # Reads two lines from file
    exec 3<"$job_root/status"
    read status 0<&3
    read arg 0<&3
    exec 3<&-
else
    status="incomplete"
fi

echo "status=$status arg=$arg" >> tej.log

if [ "$status" = running ]; then
    echo "Job is still running" >> tej.log
    cd "$job_root/stage"
    pwd
    exit 2
elif [ "$status" = incomplete ]; then
    echo "Job is incomplete" >> tej.log
    echo "Job is incomplete (submission aborted?)" >&2
    cd "$job_root/stage"
    pwd
    exit 1
else
    cd "$job_root/stage"
    pwd
    echo $arg
    exit 0
fi
