#!/bin/bash
#
# bb_get_state
#
# NOTE: Sample script used for burst buffer management. Used for development
# purposes and is not intended for production use.
#
# File system formats:
# I. BB_DIRECTORY (environment variable): Defines head of burst buffer file
#    system
#    A. .slurm_state, child of BB_DIRECTORY, contains state information, file
#       format is "TotalSize=#"
#    B. Slurm job ID number, child directories of BB_DIRECTORY, one per job
#       1. .slurm_state, child of Slurm job ID directory, contains state
#          information, file format is
#          "UserID=# JobID=# Name=name State=name Size=#"
#          (NOTE: "UserID" must be first)
#          (NOTE: Either the JobID or Name should be specified, but not both)
#

# Validate execute line
valid=0
if [[ $# -eq 1 && $1 = "get_sys" ]]; then
	valid=1
fi
if [[ $# -eq 2 && $1 = "get_job" ]]; then
	job_id=$2
	valid=1
fi
if [[ $valid -eq 0 ]]; then
	echo "Usage: $0 [get_sys | get_job #]"
	exit 1
fi

# Default BB_DIRECTORY for testing is $HOME/slurm_bb
if [[ -z "$BB_DIRECTORY" ]] ; then
	BB_DIRECTORY=$HOME/slurm_bb
fi

# Get information about a specific job's burst buffer state
if [[ $1 = "get_job" ]]; then
	if [[ -e $BB_DIRECTORY/$job_id/.slurm_state ]]; then
		cat $BB_DIRECTORY/$job_id/.slurm_state
		exit 0
	else
		echo "ENOENT=$BB_DIRECTORY/$job_id/.slurm_state"
		exit 1
	fi
fi

# Get global state information
if [[ -e $BB_DIRECTORY/.slurm_state ]]; then
	cat $BB_DIRECTORY/.slurm_state
else
	echo "ENOENT=$BB_DIRECTORY/.slurm_state"
fi

# First set bash option to avoid unmatched patterns expand as result values
shopt -s nullglob
# Then store matching file names into array
filearray=( "$BB_DIRECTORY"/* )
# Then print state of each job's burst buffer state
for file in "${filearray[@]}"; do
	if [[ -e $file/.slurm_state ]]; then
		cat $file/.slurm_state
	else
		echo "ENOENT=$file/.slurm_state"
	fi
done
exit 0
