#!/bin/bash -eu

ALL_PCP_SERVICES='pmcd,pmie,pmlogger,pmproxy'

PCP_SERVICES=${PCP_SERVICES:-${ALL_PCP_SERVICES}}; export PCP_SERVICES
PCP_DOMAIN_AGENTS=${PCP_DOMAIN_AGENTS:-''}; export PCP_DOMAIN_AGENTS
HOST_MOUNT=${HOST_MOUNT:-''}; export HOST_MOUNT
KEY_SERVERS=${KEY_SERVERS:-'localhost:6379'}; export KEY_SERVERS

mkdir -p /etc/systemd/system/pmcd.service.d
# shellcheck disable=SC2016
envsubst '$HOST_MOUNT' < /usr/share/container-scripts/pcp/10-host_mount.conf.template > /etc/systemd/system/pmcd.service.d/10-host_mount.conf
# shellcheck disable=SC2016
envsubst '$KEY_SERVERS' < /usr/share/container-scripts/pcp/pmproxy.conf.template > /etc/pcp/pmproxy/pmproxy.conf

echo "Enabling PCP services: ${PCP_SERVICES}"
for service in ${ALL_PCP_SERVICES//,/ }; do
    if [[ ",${PCP_SERVICES}," = *",${service},"* ]]; then
        systemctl enable "${service}" 2> /dev/null
    else
        # pcp-zeroconf enables some PCP services already -> disable them if not requested
        systemctl disable "${service}" 2> /dev/null
        # prevent other services from starting (due to systemd dependencies) by masking them
        systemctl mask "${service}" 2> /dev/null
    fi
done

test -n "${PCP_DOMAIN_AGENTS}" && \
    echo "Enabling PCP agents: ${PCP_DOMAIN_AGENTS}"
for agent in ${PCP_DOMAIN_AGENTS//,/ }; do
    if grep -q -- "^${agent}" /etc/pcp/pmcd/pmcd.conf; then
	continue
    fi
    if test -d "/var/lib/pcp/pmdas/${agent}"; then
        touch "/var/lib/pcp/pmdas/${agent}/.NeedInstall"
    fi
done

echo Starting systemd...
exec "$@"
