#!/bin/bash

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

# Stop unattended upgrades so that apt installs will work
# unattended upgrades are re-enabled at the end of the ansible run
systemctl stop unattended-upgrades
UNATTENDED_UPGRADES_DISABLED=20auto-upgrades-disabled
cp /usr/share/unattended-upgrades/${UNATTENDED_UPGRADES_DISABLED} /etc/apt/apt.conf.d/${UNATTENDED_UPGRADES_DISABLED}

# Enable job control. Allows us to start creating dhparam in the background right now.
{{#if isNode}}# For node, also allows us to install AlgoVPN in the background.{{/if}}
set -m

# see https://weakdh.org/sysadmin.html
/usr/local/bin/init_dhparams.sh run &

{{#if isNode}}
# touch algo log and start tailing it
ALGO_LOG=/var/log/bubble/install_algo.log
touch ${ALGO_LOG} && tail -f ${ALGO_LOG} &
{{/if}}

function kill_bg_jobs {
  for j in $(jobs -lr | tr '[]' ' ' |  awk '{print $1}') ; do
    kill %${j}
  done
{{#if isNode}}
  if [[ ! -z "${ALGO_LOG}" && -f "${ALGO_LOG}" ]] ; then
    rm -f ${ALGO_LOG}
  fi
{{/if}}
}

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

function die {
  echo 1>&2 "install_local: fatal error: ${1}"
  log "install_local: fatal error: ${1}"
{{#if isNode}}
  # stop ALGO_LOG tail job and remove log
  kill_bg_jobs
{{/if}}
  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

# touch authorized_keys to ensure it exists
touch "${AUTH_KEYS}" || die "Error touching ${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

{{#if isNode}}
# touch algo log and start tailing it
set -m
touch ${ALGO_LOG} && tail -f ${ALGO_LOG} &
{{/if}}

set -o pipefail
cd "${ANSIBLE_DIR}" && \
  virtualenv -p python3 ./venv && \
  . ./venv/bin/activate && \
  pip3 install ansible && \
  ansible-playbook ${SKIP_TAGS} --inventory ./hosts ./playbook.yml 2>&1 | tee ${LOG} \
|| die "Error running ansible. journalctl -xe = $(journalctl -xe | tail -n 50) ___openssl=$(ps auxwwwwwww | grep openssl) ___dhparams=$(cat /etc/nginx/dhparams.pem)"

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

# re-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

{{#if isNode}}# stop ALGO_LOG tail job and remove log{{/if}}
kill_bg_jobs

# ansible should have already restarted unattended-upgrades, but just in case
rm -f /etc/apt/apt.conf.d/${UNATTENDED_UPGRADES_DISABLED}
systemctl restart unattended-upgrades

exit 0
