node {
  try {
    stage('Checkout') {
      deleteDir()
      checkout scm
    }
    docker.withRegistry('https://registry-docker.fln.flnltd.com','ci-docker') {
      def image = docker.build('fln/gaf-mobile-builder', '--no-cache .')
      image.push('latest')
      try {
        docker.image(image.imageName()).inside('-u root:root') {
          stage('Build') {
            sh '''#!/bin/bash
              npm install -g \
                grunt-cli
              npm install
              npm run build:production
              npm run test

              touch `git rev-parse HEAD`
              tar --owner=root --group=root --gzip --create --file=`git rev-parse HEAD` --exclude-vcs --exclude=`git rev-parse HEAD` .
              cp `git rev-parse HEAD` `git rev-parse --abbrev-ref HEAD`
            '''
          }
          stage('Publish') {
            withCredentials(
            [
              [ $class: 'AmazonWebServicesCredentialsBinding',
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                credentialsId: 'jenkins-publisher',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
              ]
            ]) {
              sh '''#!/bin/bash
                aws s3 cp `git rev-parse HEAD` s3://freelancer-ciartifacts/gaf-mobile/`git rev-parse HEAD`
                aws s3 cp `git rev-parse --abbrev-ref HEAD` s3://freelancer-ciartifacts/gaf-mobile/refs/heads/`git rev-parse --abbrev-ref HEAD`
              '''
            }
          }
          stage('PublishToCDN') {
            withCredentials(
            [
              [ $class: 'AmazonWebServicesCredentialsBinding',
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                credentialsId: 'jenkins-publisher-mobile',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
              ]
            ]) {
              sh '''#!/bin/bash
                branch=`git rev-parse --abbrev-ref HEAD`
                if [ $branch = 'master' ]; then
                    aws s3 cp www s3://freelancer-gaf-mobile --recursive --exclude "*.html"
                fi
              '''
            }
          }
        }
      } catch(e) {
        throw e
      } finally {
        sh 'sudo chown_dir jenkins'
      }
    }
  } catch(e) {
    throw e
  }
}
