#!/bin/bash
#==============================================================================
# ephone-push.sh  —  called by extensions.conf [ring-engineer]:
#     System(/usr/local/bin/ephone-push.sh ${EXTEN} "${CALLERID(num)}" &)
#
# Purpose: wake the field engineer's phone via VoIP push BEFORE we send the
# INVITE, so a locked/backgrounded app has time to REGISTER (the Wait(2) in the
# dialplan covers the round-trip).
#
# It asks your device-registry API for the engineer's push token+platform, then
# hands off to APNs (iOS VoIP) or FCM (Android high-priority data).
#==============================================================================
set -euo pipefail

EXT="$1"                       # e.g. 6001
CALLER="${2:-Unknown}"         # customer's number
CALL_ID="$(cat /proc/sys/kernel/random/uuid)"

API="https://api.yourdomain.com"
API_KEY="REPLACE_WITH_SERVER_API_KEY"

# 1. Look up this engineer's most recent device token.
DEV_JSON="$(curl -sf -H "Authorization: Bearer ${API_KEY}" \
  "${API}/devices/lookup?extension=${EXT}")" || { echo "no device for ${EXT}"; exit 0; }

PLATFORM="$(echo "$DEV_JSON" | jq -r '.platform')"
TOKEN="$(echo "$DEV_JSON"    | jq -r '.token')"

# 2. Common call payload the app expects (see PushService CallPush).
read -r -d '' PAYLOAD <<EOF || true
{"callId":"${CALL_ID}","handle":"${CALLER}","name":"${CALLER}","ext":"${EXT}"}
EOF

case "$PLATFORM" in
  ios)
    # APNs VoIP push (topic must be <bundle-id>.voip). Uses your provider cert
    # or, preferably, a token-based (.p8) JWT. Here we defer to a small relay
    # so we don't ship APNs auth into the dialplan box.
    curl -sf -X POST "${API}/push/apns" \
      -H "Authorization: Bearer ${API_KEY}" \
      -H "Content-Type: application/json" \
      -d "{\"token\":\"${TOKEN}\",\"payload\":${PAYLOAD}}" >/dev/null
    ;;
  android)
    # FCM high-priority DATA message (data-only so our headless handler runs).
    curl -sf -X POST "${API}/push/fcm" \
      -H "Authorization: Bearer ${API_KEY}" \
      -H "Content-Type: application/json" \
      -d "{\"token\":\"${TOKEN}\",\"priority\":\"high\",\"data\":${PAYLOAD}}" >/dev/null
    ;;
  *)
    echo "unknown platform '${PLATFORM}' for ext ${EXT}" >&2
    ;;
esac

exit 0
