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

module.exports = async (options, logger) => {
  let {
    user = process.env.GCP_USER || requireValue('user'),
    token = process.env.GCP_TOKEN_PROD || requireValue('token'),
    authority = process.env.GCP_CA_PROD || requireValue('authority'),
    cluster = process.env.GCP_CLUSTER_PROD || requireValue('cluster'),
    server = process.env.GCP_SERVER_PROD || requireValue('server'),
    path = process.env.BITBUCKET_CLONE_DIR || process.cwd(),
    namespace = process.env.NAMESPACE
  } = options

  execShell(`echo Authenticating to ${cluster} as ${user}`)
  execShell(`echo ${token} | base64 -d > ${path}/kube_token`)
  execShell(`echo ${authority} | base64 -d > ${path}/kube_ca`)
  execShell(`kubectl config set-cluster ${cluster} --server=${server} --certificate-authority="${path}/kube_ca"`)
  execShell(`kubectl config set-credentials ${user} --token="$(cat ${path}/kube_token)"`)
  execShell(`kubectl config set-context default --cluster=${cluster} --user=${user}`)
  if(namespace)
    execShell(`kubectl config set-context default --namespace=${namespace}`)
  execShell(`kubectl config use-context default`)

  return 0
}