#!/bin/bash
set -e

STEP=${1:-CREATE}

JINJA_CMD="jinja2 -e jinja2_ansible_filters.AnsibleCoreFiltersExtension"
LAYEROPS_CONFIG_FILE={{ layerops_config_file }}
CONSUL_NODE_NAME=$(jq -r '.consul.nodeName' $LAYEROPS_CONFIG_FILE)

# Create Consul config files
for FILE in agent.hcl connect-enabled.hcl ports.hcl
do
$JINJA_CMD -o {{ consul_config_path }}/$FILE {{ consul_config_template_path }}/${FILE} $LAYEROPS_CONFIG_FILE
done

# Start consul
service consul start

case $STEP in
  "REPLACE")
    echo "REPLACING INSTANCE"
    # Wait for node syncronisation
    LOG_LINE=$((tail -F -n+0 {{ consul_log_file }} 2> /dev/null &) | timeout 5m grep  -m1  'Synced node info')
    [ $? != 0 ] && exit $?
  ;;
  "CREATE")
    # Wait for leader election
    LOG_LINE=$((tail -F -n+0 {{ consul_log_file }} 2> /dev/null &) | timeout 5m grep  -m1  'New leader elected')
    [ $? != 0 ] && exit $?
    LEADER=$(echo $LOG_LINE | awk 'BEGIN { FS = "payload=" } ; {print $2}')
    [ -z "$LEADER" ] && exit 1
    echo "Consul Cluster Leader: $LEADER"
  ;;
esac

# Wait for current node to be synchronised within the cluster
sleep 3

# start and enable consul template wireguard autoreload
$JINJA_CMD -o /etc/systemd/system/consul-template-wg.service {{ wireguard_template_path }}/consul-template-wg.service $LAYEROPS_CONFIG_FILE
systemctl daemon-reload
systemctl enable consul-template-wg
systemctl restart consul-template-wg

# start and enable consul error watcher
systemctl enable consul-error-watch
systemctl restart consul-error-watch

# check if consul-template-wg is running
STATUS=0
for i in $(seq 1 5)
do
  [ $i -gt 1 ] && sleep 1
  systemctl is-active consul-template-wg && STATUS=0 && break || STATUS=$?
done
if [ "${STATUS}" != "0" ]
then
  exit $STATUS
fi
