#!/bin/bash

while getopts ":i:" opt; do
  case $opt in
    i) identifier="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    exit 1
    ;;
  esac

  case $OPTARG in
    -*) echo "Option $opt needs a valid argument"
    exit 1
    ;;
  esac
done

JOBID=$(squeue -o %i -h --name ${identifier})
PRESTATE=$(squeue -o %T -h --name ${identifier})
slurmel_update_state "${JOBID}" "${PRESTATE}"

while true; do
    STATE=$(squeue -o %T -h --name ${identifier})
    if [[ ! "${STATE}" == "${PRESTATE}" ]]; then
        slurmel_update_state "${JOBID}" "${STATE}"
    fi
    if [[ "${STATE}" == "RUNNING" ]]; then
        exit 0
    elif [[ "${STATE}" == "CANCELLED" ]]; then
        exit 1
    elif [[ "${STATE}" == "FAILED" ]]; then
        exit 1
    else
        sleep 5
    fi
done