#!/bin/sh
# runit service: sleep INTERVAL seconds (default 1200), then report the
# last INTERVAL seconds of sshd brute-force attempts from the logs of
# DOCKER_CONTAINER_NAME to AbuseIPDB. runit restarts this script when it
# exits, so one invocation is one iteration of the loop.
#
# Configuration comes from the container environment:
#   DOCKER_CONTAINER_NAME  container whose logs are read (required)
#   IPABUSEDB_API_KEY      AbuseIPDB API key (required)
#   INTERVAL               seconds between runs (default 1200)
exec 2>&1

: "${INTERVAL:=1200}"

for var in DOCKER_CONTAINER_NAME IPABUSEDB_API_KEY; do
    eval "val=\${$var:-}"
    if [ -z "$val" ]; then
        echo "ipabusedb-docker-reporter: $var is not set in the environment" >&2
        # runit would otherwise retry every second and flood the log.
        sleep 60
        exit 1
    fi
done

echo "ipabusedb-docker-reporter: starting up, next report in ${INTERVAL}s"

# Sleep in the background so that SIGTERM from "sv stop" (which runsvinit
# sends on "docker stop") interrupts the wait instead of orphaning sleep.
trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM INT
sleep "$INTERVAL" &
sleeper=$!
wait "$sleeper"
trap - TERM INT

exec /usr/local/bin/ipabusedb-docker-reporter --since "${INTERVAL}s" --submit
