#!/bin/bash
set -e

JINJA_CMD="jinja2 -e jinja2_ansible_filters.AnsibleCoreFiltersExtension"
LAYEROPS_CONFIG_FILE={{ layerops_config_file }}
NOMAD_NODE_NAME=$(jq -r '.nomad.node_name' $LAYEROPS_CONFIG_FILE)

# Create Nomad config files
for FILE in nomad.hcl client.hcl server.hcl acl.hcl tls.hcl telemetry.hcl consul.hcl vault.hcl
do
$JINJA_CMD -o {{ nomad_config_path }}/$FILE {{ nomad_config_template_path }}/${FILE} $LAYEROPS_CONFIG_FILE
done

# start and enable Nomad
systemctl enable nomad
systemctl restart nomad

# Wait for current node to be register within the nomad cluster
(tail -F -n+0 {{ nomad_log_file }} &) | timeout 5m grep -q 'node registration complete'
