#!/bin/bash

error_ids=""
# Only run if this is the only instance of this script running
# note: since this script forks to run pgrep, we need -eq 2 here
# shellcheck disable=SC2126
if [[ $(pgrep -a -f "${0}" | grep -v scriptherder | wc -l) -eq 2 ]]; then
	# We sleep a deterministic amount of time, which will be between 0 an 128 m and allways the same within
	# a specific host, but will differ between hosts
	sleep $((16#$(ip a | grep "link/ether" | head -1 | awk -F ':' '{print $6}' | awk '{print $1}') / 2))m
	errors=''
	for container in $(/usr/local/bin/get_containers); do
		error_ids="${error_ids} ${container}: "
		for id in $(/usr/local/bin/nocc "${container}" files_external:list --all --output json | jq '.[].mount_id' | jq .); do
			/usr/local/bin/nocc "${container}" files_external:scan "${id}" | grep Error
			# shellcheck disable=SC2181
			if [[ ${?} -eq 0 ]]; then
				errors="${errors} ${id}"
				error_ids="${error_ids} ${id}"
			fi
		done
	done
else
	echo "Another instance of this script is already running, exiting"
	pgrep -a -f "${0}" | grep -v scriptherder
	exit 0
fi

if [[ -n "${errors}" ]]; then
	echo "Errors found in the following mounts: ${error_ids}"
	exit 1
fi
echo "No errors found"
exit 0