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

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

  const versionInfo = await getVersion(options, logger)

  let {
    file,
    org = process.env.DOCKER_ORG || 'viewdo',
    username = process.env.DOCKERHUB_USERNAME || requireValue('username'),
    password = process.env.DOCKERHUB_PASSWORD || requireValue('password'),
    path = process.env.BITBUCKET_CLONE_DIR || '.',
    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',
  } = options

  await execShell(`echo ${password} | docker login -u ${username} --password-stdin`)
  await execShell(`docker build ${file ? '-f ' + file : ''} -t ${org}/${image}:${tag} ${path}`)
  await execShell(`docker tag ${org}/${image}:${tag} ${org}/${image}:${version}`)

  // Check if the full version tag exists
  const doesTagExist = await execShell(`docker manifest inspect ${org}/${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 ${org}/${image}:${tag} ${org}/${image}:${versionInfo.major}`);
    }
    if (versionInfo.major !== undefined && versionInfo.minor !== undefined) {
      await execShell(`docker tag ${org}/${image}:${tag} ${org}/${image}:${versionInfo.major}.${versionInfo.minor}`);
    }
  }

  await execShell(`docker tag ${org}/${image}:${tag} ${org}/${image}:${build_id}`)

  await execShell(`docker image push -a ${org}/${image}`)

  return 0
}