
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',
    build_args = process.env.BUILD_ARGS || ''
  } = 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`)

  let buildArgsArray = build_args ? build_args.split(',') : [];
  let formattedArgs = buildArgsArray.length ? buildArgsArray.map(arg => `--build-arg ${arg}`).join(' ') : '';
  let buildCommand = `docker build ${formattedArgs} -t ${repository}/${project}/${image} ${path}`

  execShell(buildCommand)
  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
}