pipeline {
  agent {
    docker {
      image 'maven:3.3.9'
      args '-v /root/jenkins/data/mvn/settings.xml:/usr/share/maven/conf/settings.xml -v /root/jenkins/data/mvn/maven-repo:/data/maven-repo -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker -u root:994'
    }

  }
  stages {

    stage('Build') {
      steps {
        sh 'mvn clean package -U -Dmaven.test.skip=true'
      }
    }
    stage('Build Docker Image') {
      steps {
        sh '''mvn docker:build
IFS=$\'
\';
for info in $(docker images|grep $image_prefix/$docker_image_name);
do
    repository=`echo $info | awk \'{print $1}\'`;
    image_name=`echo $repository | awk -F \'/\' \'{print $2}\'`;
    tag=`echo $info | awk \'{print $2}\'`;
    image_id=`echo $info | awk \'{print $3}\'`;

    printf "%-35s %-25s %-10s %-17s " $repository $image_name $tag $image_id

    docker tag $image_id $registry_address/$docker_image_group_name/$docker_image_name:$tag
done
'''
      }
    }
    stage('Push Docker Image') {
      steps {
        sh '''docker login -u deployment -p deployment123 $registry_address
start_time=`date +'%Y-%m-%d,%H:%m:%S'`
docker images |grep $registry_address/$docker_image_group_name/$docker_image_name|awk \'{system("docker push " $1":"$2)}\'
end_time=`date +'%Y-%m-%d,%H:%m:%S'`'''
      }
    }
    stage('Deploy to SIT') {
      steps {
        sh '''# docker-compose pull env
curl -X PUT http://$dcui_address/api/v1/projects --data \'{"id":"\'$dcui_project_id\'"}\' -H\'Content-type: application/json\''''
        sh '''# docker-compose up
curl -X POST http://$dcui_address/api/v1/projects --data \'{"id":"\'$dcui_project_id\'"}\' -H\'Content-type: application/json\''''
      }
    }
    stage('Cleanup') {
      steps {
        sh '''if [ "$(docker images |grep /$docker_image_group_name/$docker_image_name |awk {\'print $3\'})" = "" ] ; then
           echo "No orphan images found"
           else
           docker rmi -f $(docker images |grep /$docker_image_group_name/$docker_image_name  |awk {\'print $3\'})
           fi'''
        cleanWs(deleteDirs: true)
      }
    }
  }
  environment {
    // Docker Compose UI的地址
    dcui_address = '192.168.21.102:5000'
    dcui_project_id = 'poc'
    // 私有仓库地址
    registry_address = 'nexus3.gsstcloud.com:8092'
    // mvn docker:build的镜像前缀
    image_prefix = 'dev-localhost'
    docker_image_group_name = 'poc'
    docker_image_name = 'poc-api'

  }
}
