pipeline {
    agent any

    environment {
        JENKINSONGITEA=credentials('d0e86441-2157-405f-8539-a9a9010c6ecf')
        JENKINSONMATRIXTOKEN=credentials('17d18fd7-29eb-4957-9532-ce42aaa9b4ec')
        MATRIX_ROOMID="!ViwVCXWvgsjFhMZlLX:greyn.club"
        GITEA_PROJECT="https://gitea.arg.rip/beefhavers/potterverse-wizards-are-morons"
    }
    stages {
        stage('meta: avatar'){
            when { changeset "meta/avatar.png"}
            steps {
                script{
                    //to gitea
                    sh(returnStdout: true, script:  """
                        echo "{\"image\": \"\$(base64 --wrap=0 meta/avatar.png)\"}" > post.json

                        curl -X 'POST' \
                          'https://gitea.arg.rip/api/v1/repos/beefhavers/potterverse-wizards-are-morons/avatar' \
                          -H 'accept: application/json' \
                          -H 'Authorization: token ${env.JENKINSONGITEA}' \
                          -H 'Content-Type: application/json' \
                          --data-binary @post.json

                        rm post.json
                    """)

                    //to matrix
                    env.avatarMXC=sh(returnStdout: true, script:  """
                        curl 'https://greyn.club:8448/_matrix/media/v3/upload?filename=potterverse-wizards-are-morons-avatar-\$(mktemp -u XXX).png' \
                          -X 'POST' \
                          -H 'authorization: Bearer ${env.JENKINSONMATRIXTOKEN}' \
                          -H 'Content-Type: image/png' \
                          --compressed \
                          --data-binary @meta/avatar.png \
                          | jq -r .content_uri
                        """).trim()

                    sh(returnStdout: true, script:  """
                        curl -X 'PUT' \
                          'https://greyn.club:8448/_matrix/client/v3/rooms/${env.MATRIX_ROOMID}/state/m.room.avatar' \
                          -H 'accept: application/json' \
                          -H 'authorization: Bearer ${env.JENKINSONMATRIXTOKEN}' \
                          -H 'Content-Type: application/json' \
                          -d '{
                                "url": "${env.avatarMXC}"
                            }'
                    """)
                }
            }
        }
        stage('credits'){
            when { changeset "script artifacts/credits.txt"}
            steps {
                sh "/home/adam/iHateThis.sh potterverse-wizards-are-morons"
            }
        }
    }
}
