#!/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"
ID_FILE="${ANSIBLE_HOME}/.ssh/bubble_rsa"
PUB_FILE="${ANSIBLE_HOME}/.ssh/bubble_rsa.pub"
AUTH_KEYS="${ANSIBLE_HOME}/.ssh/authorized_keys"

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

if [[ ! -f "${ID_FILE}" ]] ; then
  ssh-keygen -t rsa -q -N '' -f ${ID_FILE} || die "Error generating RSA key"
fi

# lockout the node that started us
cat "${PUB_FILE}" > "${AUTH_KEYS}" || die "Error updating ${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

sudo apt-get update -y && apt-get upgrade -y || die "Error in apt update / upgrade"
sudo apt-get -y install python3 python3-pip virtualenv || die "Error apt installing python3 or python3-pip"
sudo pip3 install setuptools psycopg2-binary || die "Error pip3 installing setuptools or psycopg2-binary"

SSH_OPTIONS="--ssh-extra-args '-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -i ${ID_FILE}'"

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