pipeline {
  agent none

  stages {
    stage('lint and test') {
      agent { docker 'docker-registry.internal.justin.tv/devinfra/chef-workspace:latest' }

      stages {
        stage('lint') {
          steps {
            sh 'cookstyle -c .rubocop.yml --cache=false'
          }
        }

        stage('test kitchen') {
          steps {
            // TODO: kitchen test --destroy=always
            sh "echo 'Test Kitchen Runs Here...'"
          }
        }
      }
    }

    stage('master branch only') {
      when { branch 'master' }

      stages {
        stage('manual test-kitchen verification') {
          // temporary; once we get test-kitchen working via CI, remove these options and input blocks
          options { timeout(time: 1, unit: 'HOURS') }

          input {
              message 'Have you validated this cookbook using test-kitchen?'
              ok 'This is the way.'
          }

          steps {
            echo 'This is the way.'
          }
        }

        stage('tag release for new version') {
          agent any

          environment {
            COOKBOOK_VERSION = sh(script: 'ruby -ne "print \\$1 if /^version\\s+\'(.+)\'/" metadata.rb', returnStdout: true).trim()
          }

          steps {
            sh "echo -e \"Cookbook Version: ${env.COOKBOOK_VERSION}\n\""

            // changes our git remote to use ssh, also fetches tags
            git branch: env.BRANCH_NAME, credentialsId: 'git-aws-read-key', url: env.GIT_URL.replace('https://', 'ssh://git@')

            sshagent(credentials: ['git-aws-read-key']) {
              sh """
                if ! (git show-ref --tags | egrep -q "refs/tags/${env.COOKBOOK_VERSION}")
                then
                  echo "Tagging new cookbook version ${env.COOKBOOK_VERSION}"
                  git tag ${env.COOKBOOK_VERSION} && git push --tags
                else
                  echo "Skipping version tag: ${env.COOKBOOK_VERSION} already exists on the git repo."
                fi
              """
            }
          }
        }
      }
    }
  }
}
