#!/bin/sh
set -eu

DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
. "$DIR/lib/common.sh"

usage() {
  echo "Usage: DockerEvents [--container NAME_OR_ID] [--since TIME] [--until TIME]" >&2
  echo "Notes:" >&2
  echo "- Requires docker events supporting --since/--until/--format" >&2
  echo "- If --since/--until are in the future, they are clamped to now" >&2
}

_ac_handle_help usage "$@"
_ac_require docker

container=""
since=""
until=""

now_utc() { date -u +%Y-%m-%dT%H:%M:%SZ; }
ago_utc() { date -u -d "$1" +%Y-%m-%dT%H:%M:%SZ; }

_ac_parse_args \
  container:str \
  since:str \
  until:str \
  -- "$@"

# Default window: last 30 minutes
if [ -z "$since" ] && [ -z "$until" ]; then
  since=$(ago_utc '30 minutes ago')
  until=$(now_utc)
elif [ -n "$since" ] && [ -z "$until" ]; then
  until=$(now_utc)
fi

# Safety: avoid blocking forever - clamp absolute timestamps to not be in the future
since=$(_ac_clamp_not_future_utc "$since")
until=$(_ac_clamp_not_future_utc "$until")

set -- docker events
[ -n "$since" ] && set -- "$@" --since "$since"
[ -n "$until" ] && set -- "$@" --until "$until"
[ -n "$container" ] && set -- "$@" --filter "container=$container"

exec "$@" --format '{{json .}}'
