#!/bin/sh
set -eu

[ -r /etc/conf.d/crm ] && . /etc/conf.d/crm

cmd="${1:-}"
phone="${2:-}"

case "$cmd" in
	dial)
		[ -n "$phone" ] || { echo "phone is required" >&2; exit 2; }
		if ! command -v pjsua >/dev/null 2>&1; then
			echo "pjsua is not installed" >&2
			exit 3
		fi
		if [ -z "${SIP_ID:-}" ] || [ -z "${SIP_REGISTRAR:-}" ] || [ -z "${SIP_USER:-}" ] || [ -z "${SIP_PASSWORD:-}" ]; then
			echo "SIP is not configured in /etc/conf.d/crm" >&2
			exit 4
		fi
		case "$phone" in
			sip:*|sips:*) target="$phone" ;;
			*)
				domain="${SIP_REGISTRAR#sip:}"
				domain="${domain#sips:}"
				domain="${domain%%;*}"
				target="sip:${phone}@${domain}"
				;;
		esac
		exec pjsua \
			--id "$SIP_ID" \
			--registrar "$SIP_REGISTRAR" \
			--realm "${SIP_REALM:-*}" \
			--username "$SIP_USER" \
			--password "$SIP_PASSWORD" \
			"$target"
		;;
	*)
		echo "usage: crm-softphone dial sip:number@example.com" >&2
		exit 2
		;;
esac
