#!/bin/bash

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

ALGO_BASE="$(cd $(dirname $0) && pwd)"
CA_PASS_FILE="/home/bubble/.BUBBLE_ALGO_CA_KEY_PASSWORD"

cd ${ALGO_BASE}

if [[ ! -f "${ALGO_BASE}/config.cfg.hbs" ]] ; then
  die "No ${ALGO_BASE}/config.cfg.hbs found"
fi

java -cp /home/bubble/current/bubble.jar bubble.main.BubbleMain generate-algo-conf --algo-config ${ALGO_BASE}/config.cfg.hbs || die "Error writing algo config.cfg"

python3 -m virtualenv --python="$(command -v python3)" .env \
  && source .env/bin/activate \
  && python3 -m pip install -U pip virtualenv \
  && python3 -m pip install -r requirements.txt \
  && ansible-playbook main.yml --skip-tags debug \
    -e "ca_password_file=${CA_PASS_FILE}
        ca_password_file_owner=bubble
        provider=local
        server=localhost
        store_cakey=true
        ondemand_cellular=false
        ondemand_wifi=false
        store_pki=true
        dns_adblocking=false
        ssh_tunneling=false
        endpoint={{ endpoint }}
        server_name={{ server_name }}" || die "Error installing algo"

# Archive configs in a place that the BackupService can pick them up
CONFIGS_BACKUP=/home/bubble/.BUBBLE_ALGO_CONFIGS.tgz
cd ${ALGO_BASE} && tar czf ${CONFIGS_BACKUP} configs && chgrp bubble ${CONFIGS_BACKUP} && chmod 660 ${CONFIGS_BACKUP} || die "Error backing up algo configs"
cd /home/bubble && tar xzf ${CONFIGS_BACKUP} && chgrp -R bubble configs && chown -R bubble configs && chmod 500 configs || die "Error unpacking algo configs to bubble home"
