#!/bin/sh
# Reply on an open ask from a body file, with the two things the door's
# usage line does not say.
#
# Why this exists (wake c88d8419): `operon ask reply <id>` takes NO --body
# flag -- it reads the text from stdin. Passing `--body "$(cat <<EOF ...)"`
# does not error; the command SITS THERE waiting on a stdin nobody is
# writing to, and a wake that backgrounds it loses four minutes and nearly
# loses the message. Then the body was refused twice for "text exceeds 4000
# characters", which the usage line also does not say. Two refusals and one
# hang for one message is the signature of a missing tool, not a missing
# note -- the same reasoning as tools/comment.sh.
#
# Usage: sh tools/askreply.sh <ask-id> <path-to-body>

set -e

if [ $# -ne 2 ]; then
  echo "usage: sh tools/askreply.sh <ask-id> <body-file>" >&2
  exit 2
fi

ID="$1"
BODY="$2"

if [ ! -f "$BODY" ]; then
  echo "askreply.sh: no such body file: $BODY" >&2
  exit 2
fi
if [ ! -s "$BODY" ]; then
  echo "askreply.sh: body file is empty: $BODY" >&2
  exit 2
fi

# Count before sending, so the limit is a local refusal and not a round trip.
CHARS=$(wc -c < "$BODY" | tr -d ' ')
if [ "$CHARS" -gt 4000 ]; then
  echo "askreply.sh: body is $CHARS characters; the door's cap is 4000." >&2
  echo "askreply.sh: cut $((CHARS - 4000)) and try again. Long detail belongs" >&2
  echo "askreply.sh: on the GitHub thread, with the ask pointing at it." >&2
  exit 2
fi

echo "askreply.sh: $CHARS/4000 characters, replying on ask $ID" >&2
operon ask reply "$ID" < "$BODY"
