#!/bin/bash
cd "$(dirname "$0")"

# As explained in https://api.slack.com/messaging/webhooks

DIR=`pwd`

CHANNEL="default"
TITLE="New message"
MESSAGE="_empty"

while getopts ":c:t:m:" opt; do
    case $opt in
    c)
        CHANNEL="$OPTARG"
        ;;
    t)
        TITLE="$OPTARG"
        ;;
    m)
        MESSAGE="$OPTARG"
        ;;
    :)
        echo "Option -$OPTARG requires an argument." >&2
        exit 1
        ;;
    esac
done

if [ "${MESSAGE}" = "_empty" ]
then
    echo "Usage:"
    echo ""
    echo "      %0 -m \"The message\" -t \"The title\" -c \"channelname\" "
    echo ""
    echo "      -m <MESSAGE>    Non-empty message is required."
    echo "      -t <TITLE>      Optional."
    echo "      -c <CHANNEL>    Channel name as configured in ${DIR}/.slack.json.  Default: \"default\"."
    echo "                      Configured channels can be listed with: ${DIR}/configure ${DIR}/.slack.json --key=channels"
    echo ""
    exit 1
fi

SLACK_URL="`./configure ./.slack.json --key=channels.${CHANNEL}.endpoint`"

if (($?))
  then
    echo "Slack channel ${CHANNEL} not configured."
    echo "Set it with:"
    echo ""
    echo "    ${DIR}/configure ${DIR}/.slack.json --key=channels.${CHANNEL}.endpoint --value=<API_ENDPOINT>"

    echo "    The API_ENDPOINT can be obtained as explained in https://api.slack.com/messaging/webhooks"
    echo "    and looks like: https://hooks.slack.com/services/XXXXXXXXX/YYYYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZZ"
    echo ""
    exit 2
fi

curl -X POST ${SLACK_URL} \
    -H 'Content-Type: application/json' -d "{\
    \"text\": \"${TITLE}\",\
    \"blocks\": [\
        {\
            \"type\": \"section\",\
            \"text\": {\
                \"type\": \"mrkdwn\",\
                \"text\": \"${MESSAGE}\"\
            }\
        }\
    ]\
}"

