captaincore/app/email-health/generate
2024-05-19 10:58:54 -04:00

108 lines
No EOL
2.9 KiB
Bash
Executable file

#!/usr/bin/env bash
#
# Runs email health check on one or more sites.
#
# `captaincore email-health generate`
#
# [<site>...]
# One or more sites to check.
#
# [@<target>]
# Target groups of sites like @all @production or @staging.
#
# [--retry=<number-of-retries>]
# Number of retries for failures. Defaults to 3.
#
# [--parallel=<number-of-checks>]
# Number of monitor checks to run at same time. Defaults to 5.
#
while read config; do
if [[ "$config" == "Error:"* ]]; then
continue
fi
declare "$config"
done <<< "$(php ${CAPTAINCORE_PATH}/lib/local-scripts/configs.php fetch)"
if [[ "${#CAPTAINCORE_ARGS}" == "0" ]]; then
echo -e "${COLOR_RED}Error:${COLOR_NORMAL} Required <site> or <target>."
exit 1
fi
run_command() {
target=$CAPTAINCORE_ARGS
# Assign default retry
if [[ $RETRY == "" ]]; then
RETRY=3
fi
# Assign default parallel
if [[ $FLAG_PARALLEL == "" ]]; then
FLAG_PARALLEL=5
fi
if [[ $target == "@all"* ]] || [[ $target == "@production"* ]] || [[ $target == "@staging"* ]]; then
target=$( captaincore site list $target --captain-id=$CAPTAIN_ID )
fi
token=$(date +"%s")
# Define location for health check
health_check_directory="$path_email_health/${token}/"
mkdir -p "$health_check_directory"
if [[ "$target" == "" ]]; then
echo "${COLOR_RED}Error:${COLOR_NORMAL} Nothing to check"
exit
fi
cd "$HOME/.captaincore/data"
echo "logging to ${health_check_directory}log.json"
# Run checks in parallel. Collect the results in log file.
( echo $target | tr ' ' '\n' | xargs -P $FLAG_PARALLEL -I {} captaincore email-health send {} $token ) 2>&1 | tee "${health_check_directory}log.json"
# Process responses
php $HOME/.captaincore/lib/local-scripts/email-health.php process $health_check_directory
for attempt in $(seq 1 $RETRY); do
undelivered_count=$( php $HOME/.captaincore/lib/local-scripts/email-health.php undelivered $health_check_directory )
if [[ $undelivered_count == "0" ]]; then
break
fi
# Skip last attempt
if [[ $attempt != $RETRY ]]; then
echo "Attempt #${attempt} checking environments for received emails.";
sleep 300
php $HOME/.captaincore/lib/local-scripts/email-health.php check $health_check_directory
continue
fi
echo "Attempt #${attempt} found $undelivered_count undelivered emails."
done
# Build emails
email_content=$( php $HOME/.captaincore/lib/local-scripts/email-health.php generate $health_check_directory )
if [[ $email_content != "" ]]; then
echo "Sending Email"
echo $email_content
undelivered_count=$( php $HOME/.captaincore/lib/local-scripts/email-health.php undelivered $health_check_directory )
# output "Response code $response for $address" per each item in array
echo $email_content | mutt -e 'set content_type=text/html' -s "Email Monitor: $undelivered_count failed deliveries" -- $captaincore_admin_email
fi
}
run_command