#!/bin/sh
if test "$#" -eq 0; then
  echo usage: ddial phone-number ... >&2
  exit 2
fi
handler="$(echo 'pjsua
ldap
firefox
mairix
ekiga' | dmenu)"

case "$handler" in
  ldap)   command="echo This is a made-up example of a command the program could run: ldapsearch -h ldap.example.com -x -t -s sub -b 'o=Example University,c=US' -LLL '(&(mobile=Thomas*))'" ;;
  ekiga)  command='ekiga -c' ;;
  pjsua)  command='st -e pjsua' ;;
  *)      command="$handler"
esac

for arg in "${@}"; do
  case "$arg" in
    tel:*|sip:*)
      url="$arg" ;;
    *)
      echo "$arg"
      exit
      if echo "${arg#+}" | grep '^[0-9- .]*$'; then
        clean_arg="$(echo "$arg" | tr -d '[. -]')"
        if test "${arg:#+}" = "${arg}"; then
          if test -n "$COUNTRY_CODE"; then
            url="tel:${COUNTRY_CODE}${clean_arg}"
          else
            echo Set COUNTRY_CODE environment variable or add + code to phone number. >&2
          fi
        else
          url="tel:${clean_arg}"
        fi
      else
        echo "Unrecognized address/number: $arg" >&2
      fi ;;
  esac
  echo "$url"
done | xargs $command
