import hudson.AbortException

node {
  checkout scm

  sh('git rev-parse HEAD > GIT_COMMIT')
  GIT_COMMIT=readFile('GIT_COMMIT').trim()
  GITHUB_OWNER='dta'
  GITHUB_REPO='necronomicon-user-api'

  stage 'build'
  withCredentials([[$class: 'FileBinding', credentialsId: 'aws_config', variable: 'AWS_CONFIG_FILE'], [$class: 'FileBinding', credentialsId: 'courierd', variable: 'COURIERD_PRIVATE_KEY'], [$class: 'StringBinding', credentialsId: 'devtools-deployment-github-api-token', variable: 'GITHUB_ACCESS_TOKEN']]) {
    try {
      sh 'manta -v -f build.json'
      dir('.manta') {
        sh """courierd -create-manifest ${GIT_COMMIT}.manifest -private-key ${env.COURIERD_PRIVATE_KEY}
          tar -czf ../${GIT_COMMIT}.tgz .
          mv ../${GIT_COMMIT}.tgz .
          aws s3 --profile deploy_artifact cp ${GIT_COMMIT}.tgz s3://devtools-deploy-artifacts/${GITHUB_OWNER}/${GITHUB_REPO}/${GIT_COMMIT}.tgz
          aws s3 --profile core_deploy_artifact cp ${GIT_COMMIT}.tgz s3://core-devtools-deploy-artifact/${GITHUB_OWNER}/${GITHUB_REPO}/${GIT_COMMIT}.tgz
        """
      }
      sh """curl -LSs -H "Authorization: token ${env.GITHUB_ACCESS_TOKEN}" -XPOST https://git-aws.internal.justin.tv/api/v3/repos/${GITHUB_OWNER}/${GITHUB_REPO}/statuses/${GIT_COMMIT} -d '{"state": "success", "target_url": "${env.BUILD_URL}", "context": "Jenkins", "description": "build stage succeeded"}'"""
    } catch (AbortException e) {
      sh """curl -LSs -H "Authorization: token ${env.GITHUB_ACCESS_TOKEN}" -XPOST https://git-aws.internal.justin.tv/api/v3/repos/${GITHUB_OWNER}/${GITHUB_REPO}/statuses/${GIT_COMMIT} -d '{"state": "failure", "target_url": "${env.BUILD_URL}", "context": "Jenkins", "description": "build stage failed"}'"""
      throw e
    }
  }

  if (env.BRANCH_NAME == 'master') {
    stage concurrency: 1, name: 'deploy'
    withCredentials([[$class: 'StringBinding', credentialsId: 'devtools-deployment-github-api-token', variable: 'GITHUB_ACCESS_TOKEN']]) {
      sh("git show ${GIT_COMMIT} --format='%s' --no-patch > COMMIT_TITLE")
      COMMIT_TITLE=readFile('COMMIT_TITLE').trim()

      sh """curl -Sfs "https://clean-deploy.internal.justin.tv/v1/deployments" \
         -H "GithubAccessToken: ${env.GITHUB_ACCESS_TOKEN}" \
         --data-urlencode "description=${COMMIT_TITLE}" \
         --data-urlencode "owner=${GITHUB_OWNER}" \
         --data-urlencode "repo=${GITHUB_REPO}" \
         --data-urlencode "ref=$GIT_COMMIT" \
         --data-urlencode "branch=master" \
         --data-urlencode "environment=dev\""""
    }
  }
}
