#!groovy

node {
    stage('Checkout') {
        checkout scm
    }

    stage('Prepare') {
        sh 'git rev-parse --verify HEAD > GIT_COMMIT'
        env.GIT_COMMIT = readFile('GIT_COMMIT').trim().substring(0, 10)
        sh 'rm GIT_COMMIT'
        def jobName = env.JOB_NAME.tokenize('/')
        print env.jobName

        // set env
        env.DOCKER_NAME="${jobName[0]}/${jobName[1]}:${env.BRANCH_NAME}-${env.GIT_COMMIT}"
        env.DOCKER_REGISTRY="docker.sebse.de"

        env.NODEJS_HOME = "${tool 'node16'}"
        env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"

        def customImage
    }

    /*stage('Test') {
        env.NODE_ENV = "test"
        print "Environment will be : ${env.NODE_ENV}"
        sh 'node -v'
        sh 'npm prune'
        sh 'npm install'
        sh 'npm test'
    }*/

    stage('Build Prod') {
        env.NODE_ENV = "production"
        print "Environment will be : ${env.NODE_ENV}"

        sh 'node -v'
        sh 'npm prune'
        sh 'npm install --production=false'
        sh 'npm run build'
        sh 'rm node_modules -rf'
        sh 'npm install --only=production'
    }

    stage('Build Docker') {
        customImage = docker.build(env.DOCKER_NAME)
    }

    stage('Deploy') {
        echo 'Push to Repo'
        docker.withRegistry("https://${DOCKER_REGISTRY}", 'docker-registry-robot-web-development') {
            /* Push the container to the custom Registry */
            customImage.push()
        }
    }

    stage('Cleanup'){
        echo 'prune and cleanup'
        sh 'npm prune'
        sh 'rm node_modules -rf'
        sh "docker rmi ${env.DOCKER_NAME} ${DOCKER_REGISTRY}/${env.DOCKER_NAME}"
        sh 'docker image prune -f'
        sh 'docker rmi $(docker images -a | grep "<none>" | awk "{print \$3}") &2>/del/null || exit 0'
    }
}
