#!/bin/bash
#
# https://watchtower.nickfedor.com/
# https://github.com/nicholas-fedor/watchtower
# https://hub.docker.com/r/nickfedor/watchtower
#
# Email notification settings below assume the gateway acting
# as a smarthost and Docker version v20.10+ is required.

image="nickfedor/watchtower:latest"
instance="watchtower"
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=$("$CAT" "/etc/timezone") \
    -e WATCHTOWER_CLEANUP=true \
    -e WATCHTOWER_DEBUG=false \
    -e WATCHTOWER_INCLUDE_STOPPED=true \
    -e WATCHTOWER_LABEL_ENABLE=true \
    -e WATCHTOWER_MONITOR_ONLY=true \
    -e WATCHTOWER_REVIVE_STOPPED=false \
    -e WATCHTOWER_NO_PULL=false \
    -e WATCHTOWER_SCHEDULE="0 0 1 * * *" \
    -e WATCHTOWER_WARN_ON_HEAD_FAILURE="never" \
    -e WATCHTOWER_NOTIFICATIONS=email \
    -e WATCHTOWER_NOTIFICATION_EMAIL_FROM="$USER@$(hostname -f)" \
    -e WATCHTOWER_NOTIFICATION_EMAIL_TO="$USER@$(hostname)"  \
    -e WATCHTOWER_NOTIFICATION_EMAIL_SERVER="host.docker.internal" \
    -e WATCHTOWER_NOTIFICATION_EMAIL_SERVER_PORT=25 \
    -e WATCHTOWER_NOTIFICATION_EMAIL_SERVER_TLS_SKIP_VERIFY=true \
    -e WATCHTOWER_NOTIFICATION_EMAIL_DELAY=15 \
    -e WATCHTOWER_NOTIFICATION_EMAIL_SUBJECTTAG="[Watchtower $("$HOSTNAME")]" \
    -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
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
