#!/bin/bash

ANSIBLE_USER="{{node.user}}"
ANSIBLE_HOME="$(cd ~{{node.user}} && pwd)"
LOG="${ANSIBLE_HOME}/.ansible.log"

function log {
  echo "${1}" >> ${LOG}
}

function die {
  echo 1>&2 "${1}"
  log "${1}"
  exit 1
}

if [[ -z "{{node.user}}" ]] ; then
  die "Invalid script: node.user property was undefined when this template was created"
fi
if [[ "$(whoami)" != "{{node.user}}" ]] ; then
  die "Must be run as {{node.user}}"
fi

ANSIBLE_DIR="${ANSIBLE_HOME}/ansible"
AUTH_KEYS="${ANSIBLE_HOME}/.ssh/authorized_keys"

if [[ ! -d "${ANSIBLE_DIR}" ]] ; then
  die "Ansible dir not found or not a directory: ${ANSIBLE_DIR}"
fi

# lockout the node that started us
cat /dev/null > "${AUTH_KEYS}" || die "Error truncating ${AUTH_KEYS} file"

# ensure proper permissions on authorized_keys file
chmod 600 "${AUTH_KEYS}" || die "Error setting permissions on ${AUTH_KEYS} file"

# add admin ssh key, if one was given
ADMIN_PUB_KEY="${ANSIBLE_DIR}/roles/bubble/files/admin_ssh_key.pub"
if [[ -f "${ADMIN_PUB_KEY}" ]] ; then
  cat "${ADMIN_PUB_KEY}" >> "${AUTH_KEYS}"
fi

SKIP_TAGS=""
if [[ -n "{{restoreKey}}" ]] ; then
  SKIP_TAGS="--skip-tags algo_related"
fi

LOG=/tmp/ansible.log
cd "${ANSIBLE_DIR}" && \
  virtualenv -p python3 ./venv && \
  . ./venv/bin/activate && \
  pip3 install ansible && \
  ansible-playbook ${SKIP_TAGS} --inventory ./hosts ./playbook.yml \
|| die "Error running ansible. journalctl -xe = $(journalctl -xe | tail -n 50)"
