#!/bin/bash

# Send message to a matrix room. API call looks like this:
# curl -XPOST -d '{"msgtype":"m.text", "body":"hello"}' "http://matrix.org/_matrix/client/api/v1/rooms/%21CvcvRuDYDzTOzfKKgh%3Alocalhost/send/m.room.message?access_token=YOUR_ACCESS_TOKEN"


set -e

cd "${1}"

exec 3>&1
exec 1>&2

# for jq
PATH=/usr/local/bin:$PATH

payload=$(mktemp /tmp/resource-in.XXXXXX)

cat > "${payload}" <&0

matrix_server_url="$(jq -r '.source.matrix_server_url' < "${payload}")"
token="$(jq -r '.source.token' < "${payload}")"
room_id="$(jq -r '.source.room_id' < "${payload}")"
msgtype="$(jq -r '.source.msgtype // "m.notice"' < "${payload}")"
data_file="$(jq -r '.source.data_file // ""' < "${payload}")"

ts="$(date +%s)"

matrix_endpoint="$matrix_server_url/_matrix/client/r0/rooms/$room_id/send/m.room.message/$ts?access_token=$token"

text_file="$(jq -r '.params.text_file // ""' < "${payload}")"
thisdata_file="$(jq -r '.params.data_file // ""' < "${payload}")"
[[ -n $thisdata_file && $thisthisdata_file != $data_file ]] && data_file="${thisdata_file}"
from="$(jq -r '.params.from // ""' < "${payload}")"
trigger="$(jq -r '.params.trigger // ""' < "${payload}")"
text="$(jq '(.params.text // "${TEXT_FILE_CONTENT}")' < "${payload}")"
thismsgtype="$(jq -r '.params.msgtype // ""' < "${payload}")"
[[ -n $thismsgtype && $thismsgtype != $msgtype ]] && msgtype="${thismsgtype}"

always_notify="$(jq -r '.params.always_notify // "false"' < "${payload}")"
debug="$(jq -r '.params.debug // "false"' < "${payload}")"
silent="$(jq -r '.params.silent // "true"' < "${payload}")"
link="$(jq -r '.params.link // "false"' < "${payload}")"
team="$(jq -r '.params.team // "main"' < "${payload}")"
prefix="$(jq -r '.params.prefix // ""' < "${payload}")"


TEXT_FILE_CONTENT=""
[[ -n "${text_file}" && -f "${text_file}" ]] && TEXT_FILE_CONTENT="$(cat "${text_file}")"
DATA_FILE_CONTENT=""
[[ -n "${data_file}" && -f "${data_file}" ]] && DATA_FILE_CONTENT="$(cat "${data_file}")"

if [[ "$always_notify" == "true" || -n "$TEXT_FILE_CONTENT" || -z "$text_file" || -n "$DATA_FILE_CONTENT" ]]
then
  TEXT_FILE_CONTENT="${TEXT_FILE_CONTENT:-_(no notification provided)_}"

  text="$(eval printf ${text} )"
  [[ -z "${text}" ]] && text="_(missing notification text)_"

  [ "${link}" == "true" ] && formatted_body="<a href=\"$ATC_EXTERNAL_URL/teams/${team}/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME\">${text}</a>"
  if [ -n "$prefix" ]; then
    prefix="$(eval printf ${prefix} )"
    text="${prefix}: ${text}"
    [ -n "${formatted_body}" ] && formatted_body="${prefix}: ${formatted_body}"
  fi

  text="$(echo -n "${text}" | jq -R -s .)"
  [ -n "${formatted_body}" ] && formatted_body="$(echo -n "${formatted_body}" | jq -R -s .)"

  [[ "${token}"   != "null" ]] && username="$(eval "printf ${token}" | jq -R -s .)"
  [[ "${room_id}" != "null" ]] && room_id="$(eval "printf ${room_id}" | jq -R -s .)"
  body="$(cat <<EOF
{
  "msgtype": "${msgtype}",
  "body": ${text}
}
EOF
  )"
#  if [ "${msgtype}" != "m.notice" ]; then
    # we can attach custom data...
    builddata="$(cat <<EOF
{
  "build_job_name": "${BUILD_JOB_NAME}",
  "build_name": "${BUILD_NAME}",
  "build_pipeline_name": "${BUILD_PIPELINE_NAME}",
  "build_id": "${BUILD_ID}",
  "atc_external_url": "${ATC_EXTERNAL_URL}"
}
EOF
    )"
    body=$(echo -n $body | jq -c ".build=$builddata")
    if [ -n "${formatted_body}" ]; then
      body=$(echo -n $body | jq -c ".formatted_body=$formatted_body")
      body=$(echo -n $body | jq -c ".format=\"org.matrix.custom.html\"")
    fi
    if [ -n "$DATA_FILE_CONTENT" ]; then
      body=$(echo -n $body | jq -c ".data=$DATA_FILE_CONTENT")
    fi
    if [ -n "${trigger}" ]; then
      body=$(echo -n $body | jq -c ".trigger=\"${trigger}\"")
    fi
#  fi

  compact_body="$(echo -n "${body}" | jq -c '.')"

  if [[ "$silent" == "true" ]]
  then
    echo "Using silent output"
    curl -s -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json' -d "${compact_body}" "${matrix_endpoint}"
  else
    curl -v -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json' -d "${compact_body}" "${matrix_endpoint}"
  fi
fi

jq -n "{version:{timestamp:\"$(date +%s)\"}}" >&3