#!/bin/bash
# This file is in the public domain.
# Send an SMS
set -eu

if [ $# -ne 1 ]
then
    echo "Usage: $0 '{\"CONTACT_PHONE\":\"+41712345678\"}'" 1>&2
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_NAME=$(basename "$0")
BASE="${SCRIPT_NAME%.sh}"

PHONE_NUMBER=$(echo "$1" | jq -r .CONTACT_PHONE)
MESSAGE=$(cat -)

# List of sub-scripts to try.
PROVIDERS="telesign clicksend"

for PROVIDER in $PROVIDERS
do
    SCRIPT_PATH="$SCRIPT_DIR/${BASE}-${PROVIDER}.sh"
    if [ -x "$SCRIPT_PATH" ]
    then
	if echo "$MESSAGE" | "$SCRIPT_PATH" "$PHONE_NUMBER"
	then
	    exit 0
	else
	    echo "$PROVIDER failed to send to $PHONE_NUMBER." 1>&2
	fi
    fi
done

echo "All SMS providers failed to send to $PHONE_NUMBER." 1>&2
exit 1
