#!/usr/bin/env bash
# This script is used to provision a zimbot with a bamboo agent.
#
# IMPORTANT: If this script is run against a host which already has an agent
# installed, it will likely register a NEW agent id with the bamboo server,
# meaning the old agent will remain in bamboo's records and go offline. Please
# check the bamboo agents page to delete any old instances:
# https://bamboo.zooxlabs.com/admin/agent/configureAgents!doDefault.action

# Also, if only the integration_test.sh script has changed, you can install that
# directly using the ansible command:
# ansible-playbook install-zimbot.yaml -i inventory.yaml -l <target hostname>
set -e

if [ ! -f ~/.vault-token ]
then
  echo "No vault token found. Please authenticate."
  echo "Login to vault using your personal account by first running:"
  echo
  echo "     vault login -method=ldap username=<you>"
  exit 1
fi

ZIMBOT_DIR=$(pwd)
INVENTORY=${ZIMBOT_DIR}/inventory.yaml
BAMBOOPLAYBOOK=${ZIMBOT_DIR}/bamboo-agent.yaml

TAGS=""
LIMIT=""
while [ -n "$1" ]
do
  case $1 in
    --tags)TAGS="$1 $2"; shift;;
    --limit)LIMIT="$1 $2"; shift;;
  esac
  shift
done

if [ -z "$LIMIT" ]
then
  echo "--limit arg required, such as 'kittsim24.zooxlabs.com' or 'all'"
  exit 1
fi

# Setup zimbot bamboo agent and start it
if [[ "$TAGS" =~ "bamboo" || -z "$TAGS" ]]
then
  pushd ../../../infra/ansible 2>&1 >/dev/null
  ansible-playbook -i ${INVENTORY} $LIMIT ${BAMBOOPLAYBOOK}
  popd 2>&1 >/dev/null
fi

# Install zimbot specific files (may use bamboo config)
ansible-playbook install-zimbot.yaml -i ${INVENTORY} ${LIMIT} ${TAGS}
