pipeline {
    agent {
      label 'puppet'
    }

    post {
        always {
            deleteDir() /* clean up our workspace */
        }
        success {
            updateGitlabCommitStatus state: 'success'
        }
        failure {
            updateGitlabCommitStatus state: 'failed'
            step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'support@confdroid.com', sendToIndividuals: true])
        }
    }

    options {
          gitLabConnection('gitlab.confdroid.com')
    }

    stages {

      stage('pull master') {
        steps {
          sshagent(['edd05eb6-26b5-4c7b-a5cc-ea2ab899f4fa']) {
            sh '''
                git config user.name "Jenkins Server"
                git config user.email jenkins@confdroid.com
                git fetch origin
              source_branch="${gitlabSourceBranch:-${BRANCH_NAME:-${GIT_LOCAL_BRANCH:-$GIT_BRANCH}}}"
              source_branch="${source_branch#origin/}"
              source_branch="${source_branch#refs/heads/}"
              if [ -z "$source_branch" ]; then
                source_branch="development"
              fi
              echo "Using source branch: $source_branch"
              # Create an isolated build branch from the triggering branch revision.
              git checkout -B jenkins-build-$BUILD_NUMBER "origin/$source_branch"
                # Merge the current master into the build branch before validation.
                git merge origin/master --no-ff || { echo "Merge conflict detected"; exit 1; }
            '''
        }
      }
    }

      stage('puppet parser') {
        steps {
          sh '''for file in $(find . -iname \'*.pp\'); do
            /opt/puppetlabs/bin/puppet parser validate --color false --render-as s --modulepath=modules $file || exit 1;
            done;'''
          }
        }

      stage('check templates') {
        steps{
          sh '''for file in $(find . -iname \'*.erb\');
            do erb -P -x -T "-" $file | ruby -c || exit 1;
            done;'''
        }
      }

      stage('puppet-lint') {
        steps {
          sh '''/usr/local/bin/puppet-lint . \\
                --no-variable_scope-check \\
                || { echo "Puppet lint failed"; exit 1; }
            '''
          }
        }

      stage('SonarScan') {
         steps {
            withCredentials([string(credentialsId: 'sonar-token', variable: 'SONAR_TOKEN')]) {
              sh '''
              /opt/sonar-scanner/bin/sonar-scanner \
                -Dsonar.projectKey=confdroid_jenkins \
                -Dsonar.sources=. \
                -Dsonar.host.url=https://sonarqube.confdroid.com \
                -Dsonar.token=$SONAR_TOKEN
                '''
              }
            }
          }

      stage('create Puppet documentation') {
        steps {
          sh '/opt/puppetlabs/bin/puppet strings'
        }
      }

      stage('update repo') {
        steps {
          sshagent(['edd05eb6-26b5-4c7b-a5cc-ea2ab899f4fa']) {
            sh '''
                git config user.name "Jenkins Server"
                git config user.email jenkins@confdroid.com
                git rm -r --cached .vscode || echo "No .vscode to remove from git"
                git add -A && git commit -am "Recommit for updates in build $BUILD_NUMBER" || echo "No changes to commit"
                git fetch origin
                git checkout -B master origin/master
                git merge --no-ff jenkins-build-$BUILD_NUMBER -m "Merge build $BUILD_NUMBER into master"
                git push origin master
            '''
        }
      }
    }
      stage('Mirror to Gitea') {
        steps {
          withCredentials([usernamePassword(
            credentialsId: 'Jenkins-gitea',
            usernameVariable: 'GITEA_USER',
            passwordVariable: 'GITEA_TOKEN')]) {
            script {
                sh '''
                  git fetch --tags origin
                  git checkout -B gitea-mirror-$BUILD_NUMBER origin/master
                  git rm -f Jenkinsfile
                  git commit -m "Remove Jenkinsfile for Gitea mirror" || echo "No changes to commit"
                  git remote get-url master >/dev/null 2>&1 \
                    && git remote set-url master https://sourcecode.confdroid.com/confdroid/confdroid_jenkins.git \
                    || git remote add master https://sourcecode.confdroid.com/confdroid/confdroid_jenkins.git
                  git -c credential.helper="!f() { echo username=${GITEA_USER}; echo password=${GITEA_TOKEN}; }; f" \
                  push --force master HEAD:refs/heads/master
                  git ls-remote --heads master | awk '{print $2}' | sed 's#refs/heads/##' | while read branch; do
                    if [ -n "$branch" ] && [ "$branch" != "master" ]; then
                      git -c credential.helper="!f() { echo username=${GITEA_USER}; echo password=${GITEA_TOKEN}; }; f" \
                      push master --delete "$branch"
                    fi
                  done
                  git -c credential.helper="!f() { echo username=${GITEA_USER}; echo password=${GITEA_TOKEN}; }; f" \
                  push master --tags
                  git ls-remote --tags master | awk '{print $2}' | sed 's#refs/tags/##' | cut -d'^' -f1 | sort -u | while read tag; do
                    if [ -n "$tag" ] && ! git show-ref --tags --verify --quiet "refs/tags/$tag"; then
                      git -c credential.helper="!f() { echo username=${GITEA_USER}; echo password=${GITEA_TOKEN}; }; f" \
                      push master ":refs/tags/$tag"
                    fi
                  done
                  '''
          }
        }
      }
    }
  }
}