#!/bin/bash

#Support Rocketchat webhooks
#ROCKETCHAT_WEBHOOK_URL="https://xxxxx/hooks/xxxx"

rocketchat_send() {
  _subject="$1"
  _content="$2"
  _statusCode="$3" #0: success, 1: error 2($RENEW_SKIP): skipped
  _debug "_statusCode" "$_statusCode"

  _hostname=`hostname -f`

  ROCKETCHAT_WEBHOOK_URL="${ROCKETCHAT_WEBHOOK_URL:-$(_readaccountconf_mutable ROCKETCHAT_WEBHOOK_URL)}"
  if [ -z "$ROCKETCHAT_WEBHOOK_URL" ]; then
    ROCKETCHAT_WEBHOOK_URL=""
    _err "You didn't specify a webhook URL yet."
    _err "Please check documentation here : https://docs.rocket.chat/administrator-guides/integrations"
    return 1
  fi
  _saveaccountconf_mutable ROCKETCHAT_WEBHOOK_URL "$ROCKETCHAT_WEBHOOK_URL"

   export _H1="Content-Type: application/json"
     _content="$(printf "*%s*\n%s" "$_subject on $_hostname" "$_content" | _json_encode)"
  _data="{\"text\": \"$_content\" }"

  response="$(_post "$_data" "$ROCKETCHAT_WEBHOOK_URL")"

  if [ "$?" = "0" ] && _contains "$response" "true"; then
    _info "rocketchat send success."
      return 0
  fi

  _err "rocketchat send error."
  _err "$response"
  return 1
}