#!/usr/bin/bash
#
# post.sh — post a work-update status to Mastodon [#743]
#
# Zero-install: uses curl against the Mastodon REST API (host-hygiene
# compliant — no packages on the host). Credentials come from the
# centralized store:
#   ~/.creds/mastodon.env   (MASTODON_URL, MASTODON_TOKEN)
# Token needs write scope; create via Mastodon → Preferences → Development.
#
# Usage:
#   post.sh [-v public|unlisted|private|direct] "status text (<=500 chars)"
#
set -euo pipefail

CREDS="${HOME}/.creds/mastodon.env"
if [ ! -r "$CREDS" ]; then
  echo "post.sh: missing $CREDS (needs MASTODON_URL, MASTODON_TOKEN)" >&2
  exit 2
fi
# shellcheck disable=SC1090
. "$CREDS"
if [ -z "${MASTODON_URL:-}" ] || [ -z "${MASTODON_TOKEN:-}" ]; then
  echo "post.sh: MASTODON_URL / MASTODON_TOKEN not set in $CREDS" >&2
  exit 2
fi

visibility="public"
if [ "${1:-}" = "-v" ]; then
  visibility="$2"
  shift 2
fi
if [ $# -lt 1 ]; then
  echo "usage: $0 [-v public|unlisted|private|direct] \"status text\"" >&2
  exit 2
fi

status="$1"
len=${#status}
if [ "$len" -gt 500 ]; then
  echo "post.sh: status too long ($len chars; hard ceiling 500)" >&2
  exit 1
fi

curl -sS --max-time 30 -X POST "$MASTODON_URL/api/v1/statuses" \
  -H "Authorization: Bearer $MASTODON_TOKEN" \
  --data-urlencode "status=$status" \
  --data-urlencode "visibility=$visibility" |
  jq -r '"posted id=\(.id) url=\(.url) visibility=\(.visibility)"'
