#!/bin/bash

# determine STUBL install location
# Copied from Apache Ant:
# https://git-wip-us.apache.org/repos/asf?p=ant.git;a=blob;f=src/script/ant;h=b5ed5be6a8fe3a08d26dea53ea0fb3f5fab45e3f
if [ -z "$STUBL_HOME" -o ! -d "$STUBL_HOME" ] ; then
  ## resolve links - $0 may be a link to stubl's home
  PRG="$0"
  progname=`basename "$0"`

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
    else
    PRG=`dirname "$PRG"`"/$link"
    fi
  done

  STUBL_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  STUBL_HOME=`cd "$STUBL_HOME" > /dev/null && pwd`
fi

# setup STUBL environment
. $STUBL_HOME/conf/stubl 

jobId=$1

if [ "$2" != "" ]; then
  partition=$2
else
  partition="$STUBL_DEFAULT_PARTITION"
fi

if [ "$3" != "" ]; then
  cluster=$3
else
  cluster="$STUBL_DEFAULT_CLUSTER"
fi

if [ "$jobId" == "" -o "$jobId" == "--help" ]; then
  echo "Usage:"
  echo "  sgetscr <job_id> [partition] [cluster]"
  echo ""
  echo "Retrieves the SLURM/SBATCH script and environment "
  echo "files for a job that is queued, running, or complete."
  echo ""
  exit
fi

curState=`squeue --job=${jobId} --clusters=${cluster} --partition=${partition} -ho "%T" 2>/dev/null | tail -n1`

# echo "curState = $curState"

if [ "${curState}" != "PENDING" ]; then
  start=`sacct -M $cluster -j $jobId -o Start -n -P -X | cut -dT -f1 | sed 's/-//g'`
  fname=$STUBL_JOBSCRIPT_ROOT_DIR/$cluster/$start/${jobId}.savescript
  if [ -f $fname ]; then
    cat $fname | tee job_${jobId}_script.txt
  else
    echo "Job script not available. jobid=$jobId and cluster=$cluster"
    echo "I looked here: $fname"
  fi
else
  fname=`scontrol show job $jobId --clusters=$cluster | grep " Command=" | cut -d= -f2 | awk '{ print $1 }'`
  if [ ! -f "$fname" ]; then
    echo "Job script not available. jobid=$jobId and cluster=$cluster"
  else  
    sudo cat $fname | tee job_${jobId}_script.txt
  fi
fi


