#!/usr/bin/env bash
# welcomebot-logs — print logs for the yttrx-welcomebot container (welcome + abuse bot).
#
# Installed at /usr/local/bin/welcomebot-logs on admin.yttrx.com.
# Source of truth: ~/yttrx-welcomebot/bin/welcomebot-logs (workstation).
# Run as root (how `ssh admin.yttrx.com` logs in); needs Docker access.
set -euo pipefail

CONTAINER="${WELCOMEBOT_CONTAINER:-yttrx-welcomebot}"
tail_n=200
follow=0
since=""
pattern=""

usage() {
  cat <<EOF
Usage: welcomebot-logs [options]

Print logs for the '$CONTAINER' container (yttrx welcome + abuse bot).

Options:
  -f, --follow         Stream new log lines (like tail -f); Ctrl-C to stop.
  -n, --tail N         Show the last N lines (default: $tail_n; 'all' for everything).
      --since WHEN     Only logs newer than WHEN (e.g. 1h, 30m, 2026-06-17, 2026-06-17T20:00).
      --abuse          Only abuse-handler lines (reports, silences, dry-run, tiers).
      --welcome        Only welcome lines.
      --ip             Only IP-scrutiny lines (classifications, ip_block writes, ipapi.is errors).
  -g, --grep PATTERN   Only lines matching PATTERN (extended regex).
  -h, --help           Show this help.

Examples:
  welcomebot-logs                  # last $tail_n lines, then exit
  welcomebot-logs -f --abuse       # follow live abuse activity only
  welcomebot-logs -n 1000 --since 24h
  welcomebot-logs -g 'acct=spammer'
  welcomebot-logs --ip --since 24h # recent signup-IP classification decisions
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    -f|--follow) follow=1 ;;
    -n|--tail)   shift; tail_n="${1:?--tail needs a value}" ;;
    --since)     shift; since="${1:?--since needs a value}" ;;
    --abuse)     pattern='welcomebot (report |auto-|\[DRY-RUN\]|tier=|silenc|holds a staff|allowlisted)' ;;
    --welcome)   pattern='welcomebot (welcomed|already welcomed|skipping non-local|queued)' ;;
    --ip)        pattern='welcomebot (flagged signup|ipapi\.is lookup failed|ip_block|unparseable ip)' ;;
    -g|--grep)   shift; pattern="${1:?--grep needs a value}" ;;
    -h|--help)   usage; exit 0 ;;
    *) echo "welcomebot-logs: unknown option: $1" >&2; usage >&2; exit 2 ;;
  esac
  shift
done

if ! command -v docker >/dev/null 2>&1; then
  echo "welcomebot-logs: docker not found in PATH" >&2; exit 1
fi
if ! docker inspect "$CONTAINER" >/dev/null 2>&1; then
  echo "welcomebot-logs: container '$CONTAINER' not found (is it deployed/running?)" >&2; exit 1
fi

args=(logs --tail "$tail_n")
[ "$follow" -eq 1 ] && args+=(--follow)
[ -n "$since" ]     && args+=(--since "$since")

# docker logs writes app output to stdout+stderr; merge then optionally filter.
if [ -n "$pattern" ]; then
  docker "${args[@]}" "$CONTAINER" 2>&1 | grep -E --line-buffered -- "$pattern" || true
else
  docker "${args[@]}" "$CONTAINER" 2>&1
fi
