#!/bin/bash
set -euo pipefail

: "${SLACK_TOKEN:?The SLACK_TOKEN environment variable is required.}"
: "${SLACK_CHANNEL:?The SLACK_CHANNEL environment variable is required.}"

upload=0
args=()

for arg; do
    case "$arg" in
        --upload)
            upload=1;;
        *)
            args+=("$arg");;
    esac
done

set -- "${args[@]}"

text="${1:?Some message text is required.}"

if [[ "$upload" == 1 ]]; then
    echo "Uploading data to Slack with the message: $text"
    curl https://slack.com/api/files.upload \
        --header "Authorization: Bearer $SLACK_TOKEN" \
        --form-string channels="$SLACK_CHANNEL" \
        --form-string title="$text" \
        --form-string filename="$text" \
        --form file=@/dev/stdin \
        --form filetype=text \
        --fail --silent --show-error \
        --http1.1 \
        --include
else
    echo "Posting Slack message: $text"
    curl https://slack.com/api/chat.postMessage \
        --header "Authorization: Bearer $SLACK_TOKEN" \
        --form-string channel="$SLACK_CHANNEL" \
        --form-string text="$text" \
        --fail --silent --show-error \
        --http1.1 \
        --include
fi
