#!/usr/bin/env bash
# dc-live [--id]  - am I on a call, and which one?
#
# Without it an agent cannot tell whether the call has finished, and a line
# can go into the chat seconds after the call closed.
#
#   dc-live        the live call in English, exit 0; "no call is live", exit 1
#   dc-live --id   just the call id, for `dc-say --call "$(dc-live --id)"`
#
# The id is the invite message's id. Chat 12 is the ROOM - long-lived and
# reusable. msg 5531 is the CALL - minted per call. Same idea as SIP's
# Call-ID (RFC 3261); Delta models a call as a message, so we get one free.
#
# It reads a file the bot writes on connect and removes on close, so it never
# touches the account lock and is safe to run mid-call, in a loop, anywhere.
# A file whose call began before the running bot started is stale (a bot
# stopped mid-call left it): no call is live, exit 1, the reason on stderr.
#
# Undelivered agent mail: when the bot holds mail it could not send
# (DC_UNDELIVERED, <DC_ROOT>/undelivered), dc-live says how many are waiting
# for a retry and how many are dead, on stderr, live call or not. --id never.
set -euo pipefail
# shellcheck source=dc-env
. "$(dirname "$(readlink -f "$0" 2>/dev/null || echo "$0")")/dc-env"
dc_help "${1:-}"
IDONLY=""; [ "${1:-}" = "--id" ] && IDONLY=1
# >>> undelivered
if [ -z "$IDONLY" ]; then
  # `|| true`: no spool yet (the usual case) or no dead/ makes find exit 1, and
  # under set -e + pipefail that killed dc-live silently with 1 ("no call is live")
  waiting=$({ find "$DC_UNDELIVERED" -maxdepth 1 -type f -name '*.json' 2>/dev/null || true; } | wc -l | tr -d ' ')
  dead=$({ find "$DC_UNDELIVERED/dead" -maxdepth 1 -type f -name '*.json' 2>/dev/null || true; } | wc -l | tr -d ' ')
  if [ "$waiting" != 0 ] || [ "$dead" != 0 ]; then
    echo "dc-live: undelivered mail to the agent: $waiting waiting, $dead dead ($DC_UNDELIVERED)" >&2
  fi
fi
# <<< undelivered
# >>> bot-pid
# A live file with no bot behind it is a lie, not a call. Say which.
# Only the bot knows its own pid: it writes DC_PID_FILE (<root>/bot.pid) once
# it holds the account, four lines (bridge/pidfile.py): its pid, its start
# time and its command line as `ps` gives them (TZ=UTC0, LC_ALL=C), and its
# root. It is THIS root's bot only if that pid is alive, `ps` gives the same
# start time and command line for it now, the command line names sessionphone,
# and the root is this one. A dead pid, or one given to another process since,
# is a stale file: not running. Argv is never searched, so a grep, a tail -f
# or another agent's bot that carries this bot's name is no bot.
# dc_bot_why: "" when the bot runs, else why not, in words.
dc_bot_why() {
  local f="$DC_PID_FILE" pid started cmd root here now
  [ -e "$f" ] || { echo "no $f: no bot has started on this root, or the one running is older than its pid file (restart it)"; return; }
  { read -r pid; read -r started; read -r cmd; read -r root; } < "$f" || true
  case "$pid" in ''|*[!0-9]*|0*|1) echo "$f names no bot's pid (${pid:-nothing})"; return ;; esac
  kill -0 "$pid" 2>/dev/null || { echo "$f is stale: pid $pid is not running"; return; }
  now="$(TZ=UTC0 LC_ALL=C ps -ww -o lstart= -p "$pid" 2>/dev/null)" || now=""
  read -r now <<<"$now" || true
  [ -n "$started" ] && [ "$now" = "$started" ] || { echo "$f is stale: pid $pid is another process now (started ${now:-?}, not ${started:-?})"; return; }
  now="$(TZ=UTC0 LC_ALL=C ps -ww -o command= -p "$pid" 2>/dev/null)" || now=""
  read -r now <<<"$now" || true
  [ -n "$cmd" ] && [ "$now" = "$cmd" ] || { echo "$f is stale: pid $pid runs another command now"; return; }
  case "$cmd" in *sessionphone*) ;; *) echo "$f names pid $pid, which is no sessionphone bot ($cmd)"; return ;; esac
  here="$(cd "$DC_ROOT" 2>/dev/null && pwd -P)" || here="$DC_ROOT"
  [ "$root" = "$here" ] || { echo "$f is another root's: its bot runs on ${root:-?}, not $here"; return; }
}
if [ -n "${DC_BOT:-}" ] && [ -z "$IDONLY" ]; then
  echo "dc-live: DC_BOT is set and IGNORED: the bot is found by its pid file, $DC_PID_FILE" >&2
fi
why="$(dc_bot_why)"
if [ -n "$why" ]; then
  if [ -z "$IDONLY" ]; then
    echo "dc-live: the bot is NOT RUNNING for $DC_ROOT - there is no call, and nothing can start one." >&2
    echo "dc-live: $why" >&2
  fi
  exit 2
fi
# <<< bot-pid
if [ ! -f "$DC_LIVE" ]; then
  [ -n "$IDONLY" ] || echo "no call is live"
  exit 1
fi
# >>> stale-live: the bot's start (bot.pid's second line, ps lstart in UTC and
# C's words). A live file whose call began before this bot started was left by
# an earlier bot stopped mid-call: no call is live. One second allowed: ps
# gives the start to the second.
started=""
{ read -r _; read -r started; } < "$DC_PID_FILE" || true
# <<< stale-live
python3 - "$DC_LIVE" "${IDONLY:-}" "$DC_CALLS_DIR" "$started" <<'PY'
import calendar, json, sys, time
try:
    d = json.load(open(sys.argv[1]))
except Exception as e:
    print(f"dc-live: live file unreadable: {e}", file=sys.stderr); sys.exit(2)
try:   # a day under 10 is space-padded
    start = calendar.timegm(time.strptime(" ".join(sys.argv[4].split()), "%a %b %d %H:%M:%S %Y"))
    since = float(d["since"])
except (ValueError, TypeError, KeyError):
    start = since = None        # cannot judge its age: the file is believed, as before
if start is not None and since < start - 1:
    if not sys.argv[2]:
        print("no call is live")
        print(f"dc-live: {sys.argv[1]} is stale: call msg {d.get('call_id')} began "
              f"{(start - since) / 60:.0f} min before the running bot started, so an earlier bot "
              f"left it (stopped mid-call); this bot removes it when it next starts", file=sys.stderr)
    sys.exit(1)
if sys.argv[2]:
    print(d.get("call_id", "")); sys.exit(0)
mins = (time.time() - d.get("since", time.time())) / 60
print(f"call msg {d.get('call_id')} - chat {d.get('chat_id')} with {d.get('caller', '?')}, up {mins:.0f} min")
print(f"  tape: {d.get('dir')}  (under {sys.argv[3]})")
print(f"  say:  dc-say --call {d.get('call_id')} {d.get('chat_id')} 'your line'")
PY
