pipeline {

    agent any

    environment {
        REGISTRY_CREDENTIALS = credentials('registry-credentials-id')
        PORTAINER_CREDENTIALS = credentials('portainer-credentials-id')
    }

    stages {

        stage('Installation') {
            steps {
                echo "start Installation"
                echo "finish Installation"
            }
        }
        stage('Build') {
            steps {
                echo "Running ${env.BUILD_ID} on ${env.JENKINS_URL}"
                echo 'Building..'
                echo "docker build -t registry.proxyq.co/jenkins/website:${env.BUILD_ID} ."
                sh "docker build -t registry.proxyq.co/jenkins/website:${env.BUILD_ID} ."
            }
        }
        stage('Testing') {
            steps {
                echo "start Testing"
                sh 'sleep 5'
                echo "finish Testing"
            }
        }
        stage('Publish') {
            steps {
                sh "docker login https://registry.proxyq.co -u ${REGISTRY_CREDENTIALS_USR} --password ${REGISTRY_CREDENTIALS_PSW}"
                sh "docker push registry.proxyq.co/jenkins/website:${env.BUILD_ID}"
            }
        }
        stage('Redeploy') {
            steps {
                script {
                    def json = """
                        {"username": "${PORTAINER_CREDENTIALS_USR}", "password": "${PORTAINER_CREDENTIALS_PSW}"}
                    """
                     def jwtResponse = httpRequest acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_JSON', validResponseCodes: '200', httpMode: 'POST', ignoreSslErrors: true, consoleLogResponseBody: true, requestBody: json, url: "https://portainer.<yourdomain>.com/api/auth"
                     def jwtObject = new groovy.json.JsonSlurper().parseText(jwtResponse.getContent())
                     env.JWTTOKEN = "Bearer ${jwtObject.jwt}"
                }
                echo "${env.JWTTOKEN}"
            }
        }
    }
}
