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

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

  const versionInfo = getVersion(options, logger)

  let {
    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 || 'latest'
  } = options

  execShell(`docker login -u ${username} -p ${password}`)
  execShell(`docker build -t ${org}/${image} ${path}`)
  execShell(`docker tag ${org}/${image} ${org}/${image}:${tag}`)
  execShell(`docker tag ${org}/${image} ${org}/${image}:${version}`)
  execShell(`docker tag ${org}/${image} ${org}/${image}:${build_id}`)

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

  return 0
}