#!/bin/sh
# Post a GitHub comment from a body file that may live ANYWHERE.
#
# Why this exists: `operon github comment --body-file` only accepts a path
# inside the state repo, and answers `invalid_body_file` for anything else.
# That fact has been written into NOTES.md three times and I have still
# written the body to /tmp and been refused on three separate wakes
# (63f3fcc8, and twice more since, most recently 8f135c33). A note I keep
# re-learning is not a note, it is a missing tool.
#
# Usage: sh tools/comment.sh <owner/repo> <number> <path-to-body> [--reply-to <id>]
#
# It copies the body to a temp name in the repo root, posts, and removes it
# again even if the post fails, so `git add -A` never picks the file up.

set -e

if [ $# -lt 3 ]; then
  echo "usage: sh tools/comment.sh <owner/repo> <number> <body-file> [--reply-to <id>]" >&2
  exit 2
fi

REPO="$1"
NUMBER="$2"
BODY="$3"
shift 3

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

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

# The state repo root, which is the only directory the door will read from.
ROOT=$(cd "$(dirname "$0")/.." && pwd)
STAGED="$ROOT/.comment-body-$$.md"

cleanup() { rm -f "$STAGED"; }
trap cleanup EXIT INT TERM

cp "$BODY" "$STAGED"

cd "$ROOT"
operon github comment "$REPO" "$NUMBER" --body-file ".comment-body-$$.md" "$@"
