#!/usr/bin/env bash
# welcomebot-signups — inspect the signup-IP classification history for yttrx-welcomebot.
#
# Installed at /usr/local/bin/welcomebot-signups on admin.yttrx.com.
# Source of truth: ~/yttrx-welcomebot/bin/welcomebot-signups (workstation).
# Reads the persistent `signup_ip` sqlite table (survives log rotation) —
# see app/main.py's record_signup_ip / IP-based signup scrutiny.
set -euo pipefail

CONTAINER="${WELCOMEBOT_CONTAINER:-yttrx-welcomebot}"
limit=20
flagged_only=0
acct_filter=""

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

Print signup-IP classification records (acct, ip, org, classification,
flagged, ip_block status, timestamp) from the welcomebot's persistent
sqlite store, newest first.

Options:
  -n, --limit N     Show the last N rows (default: $limit; 'all' for everything).
      --flagged     Only flagged (datacenter) signups.
  -a, --acct ACCT   Only rows for this acct (exact match).
  -h, --help        Show this help.

Examples:
  welcomebot-signups                  # last $limit classification decisions
  welcomebot-signups --flagged        # only datacenter-flagged signups
  welcomebot-signups -n all
  welcomebot-signups -a someuser
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    -n|--limit) shift; limit="${1:?--limit needs a value}" ;;
    --flagged)  flagged_only=1 ;;
    -a|--acct)  shift; acct_filter="${1:?--acct needs a value}" ;;
    -h|--help)  usage; exit 0 ;;
    *) echo "welcomebot-signups: unknown option: $1" >&2; usage >&2; exit 2 ;;
  esac
  shift
done

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

docker exec \
  -e SIG_LIMIT="$limit" \
  -e SIG_FLAGGED_ONLY="$flagged_only" \
  -e SIG_ACCT="$acct_filter" \
  "$CONTAINER" python3 -c '
import os
import sqlite3

conn = sqlite3.connect("/data/welcomed.db")
where, params = [], []
if os.environ.get("SIG_FLAGGED_ONLY") == "1":
    where.append("flagged = 1")
if os.environ.get("SIG_ACCT"):
    where.append("acct = ?")
    params.append(os.environ["SIG_ACCT"])

sql = "SELECT acct, ip, classification, org, flagged, ipblock_registered, classified_at FROM signup_ip"
if where:
    sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY classified_at DESC"

limit = os.environ.get("SIG_LIMIT", "20")
if limit != "all":
    sql += f" LIMIT {int(limit)}"

rows = conn.execute(sql, params).fetchall()
if not rows:
    print("(no matching signup records)")
for acct, ip, classification, org, flagged, ipblock, ts in rows:
    flag = "FLAGGED" if flagged else "-"
    ipb = "ipblock=yes" if ipblock else "ipblock=no"
    print(f"{ts}  {acct or '':20s} {ip or '':16s} {classification or '':12s} {flag:8s} {ipb:12s} {org or ''}")
'
