#!/bin/sh
#
# This script can be used as a callto: (or other) protocol handler in
# Mozilla Firefox-based browser.
# In Firefox use Preferences > Applications and set the callto handler
# to this script.

# The sflphone daemon config file
RESFILE=~/.config/sflphone/sflphonedrc

# Parse sflphonedrc and get default account id string
if [ -f "$RESFILE" ]; then

	# Use first ID
	ACCOUNTID=`grep Accounts.order $RESFILE | sed -e 's/Accounts.order=//' -e 's/\/.*//'`

	# Accounts.order is not set
	if [ -z $ACCOUNTID ]; then

		# Use first account declared in sflphone config
		ACCOUNTID="`grep -m 1 Account: $RESFILE | sed -e 's/\[//' -e 's/\]//'`"
    fi

else
    echo Fatal: Cant find sflphonedrc config file.
    exit 1
fi

# Check 1st argument (phone number)
if [ -z $1 ]; then
    echo "Error: argument 1 (phone number) not provided."
    exit 1
fi

# Cleanup destination, keeping numbers only
TO="`echo $1 | sed -e 's/[^0123456789]//g'`"

# Generate call id.
CALLID=${RANDOM}$$

dbus-send                                           \
    --type="method_call"                            \
    --dest="org.sflphone.SFLphone"                  \
    "/org/sflphone/SFLphone/CallManager"            \
    "org.sflphone.SFLphone.CallManager.placeCall"   \
    string:"$ACCOUNTID"                             \
    string:"$CALLID"                                \
    string:"$TO"

exit 0

# EOF
