pipeline {
    agent any
    stages {
        stage('pr_checks') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'mock-turtle-token', usernameVariable: 'USERNAME', passwordVariable: 'TOKEN')]) {
                    sh '''
                        PR_ID=`echo "$CHANGE_URL" | grep -Po '^http://gitea:3000/Wonderland/mock-turtle/pulls/\\K\\d+$'`
                        if [ $? -eq 0 ];
                        then
                            gitp=`git diff --word-diff=porcelain origin/${CHANGE_TARGET} | grep -e "^+[^+]" | wc -w | xargs`
                            gitm=`git diff --word-diff=porcelain origin/${CHANGE_TARGET} | grep -e "^-[^-]" | wc -w | xargs`      
                            if [ $(($gitp - $gitm)) -eq 0 ] ; then check1=true; else check1=false; fi
                            if [ $(wc -l <version) -eq 0 -a $(grep -Po "^\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}$" version) ] ; then check2=true; else check2=false; fi
                            if [ $(git diff --name-only origin/${CHANGE_TARGET} | grep version) ] ; then check3=true; else check3=false; fi
                            if $check1 && $check2 && $check3;
                            then
                                curl -X 'POST' \
                                'http://gitea:3000/api/v1/repos/Wonderland/mock-turtle/pulls/'"$PR_ID"'/merge' \
                                -H 'accept: application/json'\
                                -H 'Content-Type: application/json' \
                                -H 'Authorization: token '"$TOKEN" \
                                -d '{
                                    "Do": "merge"
                                }';
                            else
                                echo 'skipping...';
                            fi
                        fi
                    '''
                }
            }
        }
    }
}
