#!/usr/bin/env bash

# Batch processing on a single computer.
#
# Copyright (c) 2003-2022 by Reto Kromer <https://reto.ch>
#
# This Bash script is released under a 3-Clause BSD License and is provided
# "as is" without warranty or support of any kind.


# initialise constants
VERSION='2019-03-16'
SCRIPT_NAME=$(basename "${0}")
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# initialise variables
unset job_list
unset job


# process input and exit with status 1
if (( $# != 1 )); then
cat << EOF

Usage:
  ${SCRIPT_NAME} <job_list>

EOF
  exit 1
else
  job_list="${1}"
fi


# print an error message and exit with status 1
abort() {
  echo -e "${RED}${1:-An unknown error occurred.\a}${NC}"
  exit 1
}


# get date-and-time stamp
date_time() {
  TZ='UTC' date +'[%F %T %Z]'
}


# verify input validity
if [[ ! -f "${job_list}" ]]; then
  abort "'${job_list}' is not a file."
fi

# start processing
echo "$(date_time) ${SCRIPT_NAME} ${VERSION}"
echo "$(date_time) START"
echo "$(date_time) batch file '${job_list}'"

# batch processing
while IFS= read -r job; do
  ${job} &>/dev/null & wait $!
  if (( $? == 0 )); then
    echo -e "$(date_time) ${BLUE}OK${NC} '${job}'"
  else
    echo -e "${RED}$(date_time) ERROR${NC} '${job}'"
  fi
done < "${job_list}"

# end processing
echo "$(date_time) END"
