#!/bin/bash
# Apply the packaged Ansible role to this host.
#
# The role is the same one used to build the golden image; converge.yml selects
# the subset that is safe to re-apply to a device that is already in service.
# Site-specific addresses come from /etc/body-shape-device/site.yml, which
# provisioning writes and which no package ever overwrites.
set -Eeuo pipefail

ansible_dir=/usr/share/body-shape-device/ansible
playbook="${ansible_dir}/converge.yml"
interpreter=/opt/body-shape-device-config/venv/bin/ansible-playbook
site_file=/etc/body-shape-device/site.yml

if [[ "${EUID}" -ne 0 ]]; then
    echo "body-shape-device-converge must run as root" >&2
    exit 1
fi

for required in "${playbook}" "${interpreter}" "${site_file}"; do
    if [[ ! -e "${required}" ]]; then
        echo "missing ${required}; run provisioning on this host first" >&2
        exit 1
    fi
done

cd "${ansible_dir}"
export LC_ALL=C.UTF-8
export LANG=C.UTF-8
export ANSIBLE_CONFIG="${ansible_dir}/ansible.cfg"
# Ansible is already running as root here, so become is a no-op and must never
# prompt; a prompt would hang the unattended update agent forever.
export ANSIBLE_BECOME_ASK_PASS=False

exec "${interpreter}" -i inventory/localhost.yml "${playbook}" "$@"
