#!/bin/bash

# How to exclude worker(s)
# ./check_supervisord --exclude=worker1,worker4,worker9

# Create empty array for error list
E_LIST=()

# Check status
for i in $(supervisorctl status | awk -F ' ' '{print $1";"$2}');
do
    if ! echo $i | grep -q "RUNNING"; then
        E_LIST+=("$(echo $i | awk -F ';' '{print $1}')")
    fi
done

# Remove items from array if needed
if [[ $1 == *"--exclude="* ]]; then
    EXCL_LIST=$(echo $1 | awk -F '=' '{print $2}')
    EXCL_ARR=(${EXCL_LIST//,/ })
    for delete in "${EXCL_ARR[@]}"; do
      for i in "${!E_LIST[@]}"; do
        if [[ ${E_LIST[i]} = $delete ]]; then
         unset 'E_LIST[i]'
        fi
      done
    done
fi

# Output result
if [ ${#E_LIST[@]} -eq 0 ]; then
    echo "OK - All workers are running!"
    exit 0
else
    printf -v J_LIST '%s ' "${E_LIST[@]}"
    echo "CRITICAL - The following workers are not running: ${J_LIST%}"
    exit 2
fi
