#!/bin/bash

if [ -z "$2" ]; then
  echo -e "WARNING!!\nYou need to pass the WEBHOOK_URL environment variable as the second argument to this script.\nFor details & guide, visit: https://github.com/DiscordHooks/gitlab-ci-discord-webhook" && exit
fi

echo -e "[Webhook]: Sending webhook to Discord...\\n";

case $1 in
  "commit" )
    EMBED_COLOR=1763578
    STATUS_MESSAGE="Passed"
    ;;

  "success" )
    EMBED_COLOR=3066993
    STATUS_MESSAGE="Passed"
    ;;

  "failure" )
    EMBED_COLOR=15158332
    STATUS_MESSAGE="Failed"
    ;;

  * )
    EMBED_COLOR=0
    STATUS_MESSAGE="Status Unknown"
    ;;
esac

TMP_AUTHOR_NAME="$(git log -1 "$CI_COMMIT_SHA" --pretty="%aN")"
COMMIT_TAG=${CI_COMMIT_TAG:-"1.0.0"}
PIPELINE_URL=${CI_PIPELINE_URL:-"https://lacaleche.cc"}
AUTHOR_NAME=${TMP_AUTHOR_NAME:-"Malo"}

FIELDS='[
    {
      "name": "Version",
      "value": "'"$COMMIT_TAG"'",
      "inline": true
    },
    {
      "name": "Link",
      "value": "[WizardJourney-'"$COMMIT_TAG"'](https://gitlab.lacaleche.cc/la-caleche/utils/resource-pack/-/jobs/'"$CI_JOB_ID"'/artifacts/download?file_type=archive)"
    }
  ]'
NAME_TITLE="Resource pack update"
DESCRIPTION="A new version for the resource pack is available !"

TIMESTAMP=$(date --utc +%FT%TZ)
WEBHOOK_DATA='{
  "username": "Gitlab",
  "avatar_url": "https://gitlab.com/favicon.png",
  "timestamp": "'"$TIMESTAMP"'",
  "embeds": [ {
    "color": '$EMBED_COLOR',
    "author": {
      "name": "'"$NAME_TITLE"'",
      "url": "'"$PIPELINE_URL"'",
      "icon_url": "https://cdn.lacaleche.cc/wizard-journey.png"
    },
    "description": "'"$DESCRIPTION"'",
    "fields": '$FIELDS'
  } ]
}'

echo -e $WEBHOOK_DATA
echo -e "curl --fail --progress-bar -A \"GitLabCI-Webhook\" -H Content-Type:application/json -H X-Author:\"La Calèche#5712\" -d \"$WEBHOOK_DATA\" \"$2\""
(curl --fail --progress-bar -A "GitLabCI-Webhook" -H Content-Type:application/json -H X-Author:"La Calèche#5712" -d "$WEBHOOK_DATA" "$2" \
  && echo -e "\\n[Webhook]: Successfully sent the webhook.") || echo -e "\\n[Webhook]: Unable to send webhook."
