apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: giteacomment
spec:
  description: Send file content to a comment of the pullrequest gitea
  workspaces:
  - name: source
  - name: gitea-access-token
  params:
  - name: apiurl
  - name: requestid
  - name: title
  - name: filepath
  steps:
  - name: exec
    image: alpine
    command:
      - /bin/sh
    args:
      - '-c'
      - |
        #set -e

        cd $(workspaces.source.path)

        echo ""
        echo "== INSTALL DEPENDENCIES ==================================="
        apk add jq curl

        echo ""
        echo "== SEND COMMENT TO GITEA ================================="

        if [[ -n "$(params.title)" ]]; then
          sed -i '1i\# $(params.title)' $(params.filepath)
        fi

        RESULT=$(cat $(params.filepath))
        rm -f $(params.filepath)
        TOKEN_PATH="$(workspaces.gitea-access-token.path)"
        GITEA_ACCESS_TOKEN="$(cat ${TOKEN_PATH}/access_token)"
        APIURL=$(params.apiurl)/issues/$(params.requestid)/comments?access_token=${GITEA_ACCESS_TOKEN}
        RESULT_ESCAPED=$(jq --null-input --arg result "${RESULT}" '$result')
        BODY="{\"body\": ${RESULT_ESCAPED}}"
        echo ${BODY}

        curl -X 'POST' \
          ${APIURL} \
          -s \
          -H 'accept: application/json' \
          -H 'Content-Type: application/json' \
          -d "${BODY}"

        echo ""
        echo ""