#!/bin/bash
#
# https://github.com/containrrr/shoutrrr/tree/main
# https://github.com/RafhaanShah/Container-Mon
#
# Email notification settings below assume the gateway acting
# as a smarthost and Docker version v20.10+ is required.

image="ghcr.io/rafhaanshah/container-mon"
instance="containermon"
networks=""
outfile=""
volume=""

MSG_MISSINGDEP="Fatal: missing dependency"

# Checks the dependencies.
TR=$(which tr 2>/dev/null)
if [ -z "$TR" ]; then echo "$MSG_MISSINGDEP tr."; exit 1 ; fi
for item in cat dirname docker hostname
do
    if [ -n "$(which $item)" ]
    then export $(echo $item | "$TR" '[:lower:]' '[:upper:]')=$(which $item)
    else echo "$MSG_MISSINGDEP $item." >&2; exit 1; fi
done

# Stops and removes the container (if necessary).
if [ -n "$("$DOCKER" ps -q -f name=$instance)" ]
then "$DOCKER" stop "$instance"; fi
if [ -n "$("$DOCKER" ps -a -q -f name=$instance)" ]
then "$DOCKER" rm "$instance"; fi

# Checks for an upgrade.
$DOCKER pull "$image"

# Creates the container.
$DOCKER create \
    -e TZ="Europe/Budapest" \
    -e CONTAINERMON_CHECK_EXIT_CODE=false \
    -e CONTAINERMON_CHECK_STOPPED=false \
    -e CONTAINERMON_CRON="*/2 * * * *" \
    -e CONTAINERMON_FAIL_LIMIT=1 \
    -e CONTAINERMON_NOTIFICATION_URL="smtp://host.docker.internal:25/?from=$USER@$("$HOSTNAME" -f)&to=$USER@$("$HOSTNAME")&subject=[[Containermon $(hostname)]]" \
    -e CONTAINERMON_HEALTHY_NOTIFICATION_URL="smtp://host.docker.internal:25/?from=$USER@$("$HOSTNAME" -f)&to=$USER@$("$HOSTNAME")&subject=[[Containermon $(hostname)]]" \
	-e CONTAINERMON_NOTIFY_HEALTHY=true \
    -e CONTAINERMON_MESSAGE_PREFIX="" \
    -e CONTAINERMON_USE_LABELS=true \
    -v /var/run/docker.sock:/var/run/docker.sock \
    --add-host="host.docker.internal:host-gateway" \
    --restart unless-stopped \
    --label "com.centurylinklabs.watchtower.enable=true" \
    --name $instance $image

# Connects it to the network(s).
if [ -n "$networks" ]; then
    for network in $networks
    do
        # Checks the network, creates it if necessary.
        if [ -z "$("$DOCKER" network ls -q -f name=$network)" ]
        then "$DOCKER" network create -d bridge "$network"; fi
        # Then connects.
        $DOCKER network connect $network $instance
    done
fi

# Finally launches it.
$DOCKER start $instance
# Adds the time zone handler package to the running container.
$DOCKER exec  $instance sh -c "apk add tzdata"
if [ -n "$outfile" -a -w "$("$DIRNAME" "$outfile")" ]; then
    # Sets a background process to collect the image's output.
    # This process will automatically terminate when the image stops.
    "$DOCKER" logs -f $instance >>"$outfile" 2>&1 &
fi
