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

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

  const versionInfo = await getVersion(options, logger)

  let {
    file,
    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 || versionInfo.is_prerelease ? 'next' : 'latest',
    build_args = process.env.BUILD_ARGS || ''
  } = options


  await execShell(`echo ${keyfile} | base64 -d > /tmp/key-file.json`)
  await execShell(`gcloud auth activate-service-account --key-file /tmp/key-file.json`)
  await execShell(`gcloud config set project ${project} -q`)
  await 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 ${file ? '-f ' + file : ''} ${formattedArgs} -t ${repository}/${project}/${image}:${tag} ${path}`

  await execShell(buildCommand)
  await execShell(`docker tag ${repository}/${project}/${image}:${tag} ${repository}/${project}/${image}:${version}`)

  // Check if the full version tag exists
  const doesTagExist = await execShell(`docker manifest inspect ${repository}/${project}/${image}:${version}`)
    .then(() => true)
    .catch(() => false);

  // If the full version tag does not exist and it's not a prerelease,
  // then tag with the major and minor versions.
  if (!doesTagExist && !versionInfo.is_prerelease) {
    if (versionInfo.major !== undefined) {
      await execShell(`docker tag ${repository}/${project}/${image}:${tag} ${repository}/${project}/${image}:${versionInfo.major}`);
    }
    if (versionInfo.major !== undefined && versionInfo.minor !== undefined) {
      await execShell(`docker tag ${repository}/${project}/${image}:${tag} ${repository}/${project}/${image}:${versionInfo.major}.${versionInfo.minor}`);
    }
  }

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