#!/usr/bin/env bash set -eEuo pipefail readonly REPO_DIR="/opt/fapg/fapg-daq" readonly NODE_BIN="${REPO_DIR}/roles/daq-node/bin/fapg-daq-node" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" readonly SCRIPT_DIR readonly SERVICE_NAME="fapg-daq-node.service" readonly SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}" readonly ENV_DIR="/etc/fapg-daq" readonly ENV_FILE="${ENV_DIR}/daq.conf" readonly STATE_DIR="/var/lib/fapg-daq" readonly RUN_DIR="/run/fapg-daq" readonly RUN_USER='fapg-daq' readonly RUN_GROUP='fapg-daq' readonly SERIAL_DEVICE='' readonly READ_INTERVAL=5 readonly MQTT_HOST='fapg-daq-five-01' readonly MQTT_PORT='1883' readonly MQTT_USERNAME='fapg_zero' MQTT_PASSWORD='' function die() { echo "ERROR: $*" >&2 exit 1 } function require_root() { if [[ "$(id -u)" -ne 0 ]]; then die "$0 requires superuser privileges." fi } function install_os_dependencies() { apt-get update apt-get install -y \ perl \ libnet-mqtt-simple-perl \ libdevice-serialport-perl echo "Installed all OS dependencies." } 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 "${STATE_DIR}" \ --no-create-home \ --disabled-login \ "${RUN_USER}" fi # USB serial devices are normally accessible to members of dialout. usermod -aG dialout "${RUN_USER}" echo "Created runtime user ${RUN_USER}, group ${RUN_GROUP}." } check_repo_layout() { [[ -d "${REPO_DIR}" ]] || die "Repo not found at ${REPO_DIR}." [[ -x "${NODE_BIN}" ]] || die "${NODE_BIN} does not exist or is not executable." mkdir -p "${STATE_DIR}" "${RUN_DIR}" chown "${RUN_USER}:${RUN_GROUP}" "${STATE_DIR}" "${RUN_DIR}" echo "Verified layout of repo at ${REPO_DIR}." } function write_env_file() { mkdir -p "${ENV_DIR}" # TODO: print diff of existing and proposed env file if [[ -f "${ENV_FILE}" ]]; then echo "${ENV_FILE} already exists; leaving it unchanged." chown root:"${RUN_GROUP}" "${ENV_FILE}" chmod 0640 "${ENV_FILE}" return fi if [[ -z "${MQTT_PASSWORD:-}" ]]; then read -rsp "MQTT password for user '${MQTT_USERNAME}': " MQTT_PASSWORD echo fi [[ -n "${MQTT_PASSWORD:-}" ]] || die "MQTT_PASSWORD is required." # TODO: unsafe! cat > "${ENV_FILE}" <> "${ENV_FILE}" fi chown root:"${RUN_GROUP}" "${ENV_FILE}" chmod 0640 "${ENV_FILE}" } function write_systemd_service() { install -m 0644 -o root -g root \ "${SCRIPT_DIR}/etc/systemd/system/fapg-daq-node.service" \ "${SERVICE_FILE}" } function enable_service() { systemctl daemon-reload systemctl enable "${SERVICE_NAME}" systemctl restart "${SERVICE_NAME}" } show_status() { cat <<"EOF" Deployment complete. Current service state: EOF systemctl --no-pager --full status "${SERVICE_NAME}" } function main() { require_root install_os_dependencies # install_perl_dependencies create_runtime_user check_repo_layout write_env_file write_systemd_service enable_service show_status } main "$@"