#!/usr/bin/env bash set -eEuo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly SCRIPT_DIR readonly PASSWD_FILE="/etc/mosquitto/passwd" readonly BROKER_SERVICE_NAME="mosquitto.service" readonly HUB_STATUS_SERVICE_NAME="fapg-daq-hub-status.service" readonly HUB_STATUS_SERVICE_FILE="/etc/systemd/system/${HUB_STATUS_SERVICE_NAME}" readonly REPO_DIR="/opt/fapg/fapg-daq" readonly HUB_STATUS_BIN="${REPO_DIR}/roles/daq-hub/bin/fapg-daq-hub-status" readonly ENV_DIR="/etc/fapg-daq" readonly HUB_STATUS_ENV_FILE="${ENV_DIR}/hub-status.env" readonly RUN_USER="fapg-daq" readonly RUN_GROUP="fapg-daq" readonly MQTT_HOST="127.0.0.1" readonly MQTT_PORT="1883" readonly MQTT_USERNAME="fapg_hub" readonly HUB_STATUS_INTERVAL="5" HUB_MQTT_PASSWORD="" function die() { echo "ERROR: $*" >&2 exit 1 } function require_root() { if [[ "${EUID}" -ne 0 ]]; then die "run as root, e.g. sudo $0" fi } function passwd_has_user() { local user="$1" [[ -f "${PASSWD_FILE}" ]] || return 1 grep -qE "^${user}:" "${PASSWD_FILE}" } function ensure_mosquitto_password() { local user="$1" if passwd_has_user "${user}"; then echo "Mosquitto password for ${user} already exists; leaving it unchanged." return fi echo "Enter password for ${user}" if [[ -f "${PASSWD_FILE}" ]]; then mosquitto_passwd "${PASSWD_FILE}" "${user}" else mosquitto_passwd -c "${PASSWD_FILE}" "${user}" fi } function read_hub_mqtt_password() { if [[ -n "${HUB_MQTT_PASSWORD:-}" ]]; then return fi read -rsp "MQTT password for user '${MQTT_USERNAME}': " HUB_MQTT_PASSWORD echo [[ -n "${HUB_MQTT_PASSWORD:-}" ]] || die "MQTT password is required." } function ensure_hub_mosquitto_password() { if passwd_has_user "${MQTT_USERNAME}"; then echo "Mosquitto password for ${MQTT_USERNAME} already exists; leaving it unchanged." return fi read_hub_mqtt_password if [[ -f "${PASSWD_FILE}" ]]; then mosquitto_passwd -b "${PASSWD_FILE}" "${MQTT_USERNAME}" "${HUB_MQTT_PASSWORD}" else mosquitto_passwd -b -c "${PASSWD_FILE}" "${MQTT_USERNAME}" "${HUB_MQTT_PASSWORD}" fi } function install_os_dependencies() { apt update && apt install -y \ perl \ mosquitto \ mosquitto-clients \ libnet-mqtt-simple-perl } function create_runtime_user() { if ! getent group "${RUN_GROUP}" > /dev/null; then addgroup --system "${RUN_GROUP}" fi if ! id "${RUN_USER}" > /dev/null 2>&1; then adduser \ --system \ --ingroup "${RUN_GROUP}" \ --home /var/lib/fapg-daq \ --no-create-home \ --disabled-login \ "${RUN_USER}" fi } function check_repo_layout() { [[ -d "${REPO_DIR}" ]] || die "Repo not found at ${REPO_DIR}." [[ -x "${HUB_STATUS_BIN}" ]] || die "${HUB_STATUS_BIN} does not exist or is not executable." } function write_hub_status_env_file() { mkdir -p "${ENV_DIR}" if [[ -f "${HUB_STATUS_ENV_FILE}" ]]; then echo "${HUB_STATUS_ENV_FILE} already exists; leaving it unchanged." chown root:"${RUN_GROUP}" "${HUB_STATUS_ENV_FILE}" chmod 0640 "${HUB_STATUS_ENV_FILE}" return fi read_hub_mqtt_password cat > "${HUB_STATUS_ENV_FILE}" <