
const getVersion = require ('./services/version')
const {
  requireValue,
  execShell
  } = require('./services/utils')

module.exports = async (options, logger) => {

  const versionInfo = getVersion(options, logger)

  let {
    keyfile = process.env.GCP_KEY_FILE || requireValue('keyfile'),
    project = process.env.GCP_PROJECT || requireValue('project'),
    repository = process.env.GCP_REPO_URL || requireValue('repository'),
    path = process.env.BITBUCKET_CLONE_DIR || requireValue('path'),
    image = process.env.BITBUCKET_REPO_SLUG || requireValue('image'),
    version = process.env.VERSION || versionInfo.version || requireValue('version'),
    build_id = process.env.BUILD_ID || versionInfo.build_id || requireValue('build'),
    tag = process.env.TAG || 'latest'
  } = options

  execShell(`echo ${keyfile} | base64 -d > /tmp/key-file.json`)
  execShell(`gcloud auth activate-service-account --key-file /tmp/key-file.json`)
  execShell(`gcloud config set project ${project} -q`)
  execShell(`gcloud auth configure-docker -q`)

  execShell(`docker build -t ${repository}/${project}/${image} ${path}`)
  execShell(`docker tag ${repository}/${project}/${image} ${repository}/${project}/${image}:${tag}`)
  execShell(`docker tag ${repository}/${project}/${image} ${repository}/${project}/${image}:${version}`)
  execShell(`docker tag ${repository}/${project}/${image} ${repository}/${project}/${image}:${build_id}`)
  execShell(`docker image push -a ${repository}/${project}/${image}`)
  return 0
}