#!/bin/bash
# whp-oom-tagger — on each cgroup OOM-kill, emit an enriched syslog line tagged
# with the WHP customer (domain/user) resolved locally from docker labels.
# Flows via rsyslog -> home Graylog. No external dependencies beyond docker+journald.
handle() {
  local line="$1" cid short proc info name domain user site msg
  case "$line" in
    *oom-kill:*docker-*.scope*) ;;
    *) return ;;
  esac
  cid=$(printf '%s\n' "$line" | grep -oE 'docker-[0-9a-f]{12,64}\.scope' | head -1 | sed -E 's/^docker-([0-9a-f]+)\.scope$/\1/')
  [ -z "$cid" ] && return
  short=${cid:0:12}
  proc=$(printf '%s\n' "$line" | grep -oE 'task=[^,]+' | head -1 | cut -d= -f2)
  info=$(docker inspect "$cid" --format '{{.Name}}|{{index .Config.Labels "whp.domain"}}|{{index .Config.Labels "whp.user"}}|{{index .Config.Labels "whp.site_id"}}' 2>/dev/null)
  name=$(printf '%s' "$info" | cut -d'|' -f1 | sed 's#^/##')
  domain=$(printf '%s' "$info" | cut -d'|' -f2)
  user=$(printf '%s' "$info" | cut -d'|' -f3)
  site=$(printf '%s' "$info" | cut -d'|' -f4)
  msg="oom_kill container=$short name=${name:-unknown} domain=${domain:-unknown} user=${user:-unknown} site_id=${site:-0} process=${proc:-unknown}"
  if [ -n "$DRY_RUN" ]; then echo "$msg"; else logger -t whp-oom -- "$msg"; fi
}
if [ "$1" = "--stdin" ]; then
  while IFS= read -r l; do handle "$l"; done
else
  journalctl -kf -o cat --since now 2>/dev/null | while IFS= read -r l; do handle "$l"; done
fi
