#!/usr/bin/env bash

# Passed variable. May be SUCCESS or FAILURE value
BUILD_RESULT=$1

PROPS=""
MESSAGE=""
VERSION=""
RESULT=""
if [ "$BUILD_RESULT" != "SUCCESS" ]; then
    MESSAGE="**Failed**"
    RESULT=":no_entry:"
else
	
    RELEASE_NOTES=$(git log -5 --pretty=format:"{\"short\":false, \"title\":\"%h (%cn)\", \"value\": \"%s\"}")
	RELEASE_NOTES="$(echo "$RELEASE_NOTES" | tr '\n' ',' | sed 's/.$//' )"
    MESSAGE="sent to **TestFlight**"
	echo $RELEASE_NOTES
	PROPS=", \"props\":{\"attachments\": [{\"color\": \"#2A592A\", \"fields\": [$RELEASE_NOTES]}]}"
 
    if [ "$CI_COMMIT_TAG" ~= ^[1-9]{1}\d*\.\d+\.\d+$ ]; then
        VERSION="**$CI_COMMIT_TAG**"
        RESULT=":bulb:"
    else
        VERSION=""
        RESULT=":white_check_mark:"
    fi
fi

POST_MESSAGE="$RESULT :iphone: :chestnut: **NutPlayer Flutter**$VERSION build **$CI_PIPELINE_IID** from branch **$CI_COMMIT_REF_NAME** $MESSAGE"

curl \
	-i \
	-X POST \
	-H "Content-Type: application/json" \
	-H "Authorization: Bearer $K8S_SCOTTY_TOKEN" \
	-d "{\"channel_id\":\"$K8S_MATTERMOST_CHANNEL\", \"message\":\"$POST_MESSAGE\" $PROPS}" \
	$K8S_MATTERMOST_HOST/api/v4/posts