#!/usr/bin/env bash
# dc-call [--profile public] [--voice NAME] [--greeting TEXT] CHAT - ring a
# Delta Chat chat (audio call) as this agent. The phone rings; the bot waits
# up to 120 s. What is said on the call reaches the agent as mail; dc-say
# CHAT speaks. --voice / --greeting: a chosen opening line and voice for
# this call.
# CHAT is a chat number or a channel NAME from the owner's allow-list
# (channels.txt). A chat that is not listed is REFUSED: exit 3, the list's
# path on stderr, nothing sent, even with DC_TAKEN_WAIT=0.
# Exit: 0 sent, the bot's ack says so; 3 refused or no bot took it, nothing
# sent; 4 NOT CONFIRMED - the bot took it and wrote no ack, so it may not have
# gone (its log: DC_LOG). 1 usage, 2 could not run.
set -euo pipefail
# shellcheck source=dc-env
. "$(dirname "$(readlink -f "$0" 2>/dev/null || echo "$0")")/dc-env"
dc_help "${1:-}"
PROFILE=""; VOICE=""; GREETING=""
while true; do
  case "${1:-}" in
    --profile)  PROFILE="${2:?--profile needs a NAME}"; shift 2 ;;
    --voice)    VOICE="${2:?--voice needs a NAME}"; shift 2 ;;
    --greeting) GREETING="${2:?--greeting needs TEXT}"; shift 2 ;;
    *) break ;;
  esac
done
[ $# -eq 1 ] || { echo "usage: dc-call [--profile public] [--voice NAME] [--greeting TEXT] CHAT  (CHAT: a chat number or a channel name)" >&2; exit 1; }
OUT="$(dc_outbox "$PROFILE")" || exit 2
dc_precheck chat "$1" call "$PROFILE" || exit $?
dc_job "$OUT" "$(python3 -c 'import json,sys;j=json.loads(sys.argv[1]);j.update({"voice":sys.argv[2]} if sys.argv[2] else {});j.update({"greeting":sys.argv[3]} if sys.argv[3] else {});print(json.dumps(j))' "$DC_DEST" "$VOICE" "$GREETING")"
echo "dc-call: $DC_DONE${VOICE:+ as $VOICE}${PROFILE:+ on profile $PROFILE}"
