#!/bin/bash
# Deploy Monit monitoring for opendeviationbar on bigblack
# Run as root: sudo bash scripts/deploy_monit.sh
#
# Installs monit, copies configs and alert scripts, enables the service.
# Idempotent — safe to re-run after config changes.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"
MONIT_DIR="${REPO_DIR}/deploy/monit"

# Verify running as root
if [ "$(id -u)" -ne 0 ]; then
    echo "ERROR: must run as root (sudo bash $0)" >&2
    exit 1
fi

# Verify config files exist
for f in opendeviationbar.conf obdpy-monit-alert.sh obdpy-check-heartbeat-timer.sh; do
    if [ ! -f "${MONIT_DIR}/${f}" ]; then
        echo "ERROR: ${MONIT_DIR}/${f} not found" >&2
        exit 1
    fi
done

echo "=== Installing monit ==="
if ! command -v monit &>/dev/null; then
    apt-get update -qq && apt-get install -y -qq monit
else
    echo "monit already installed: $(monit --version | head -1)"
fi

echo "=== Deploying config ==="
cp "${MONIT_DIR}/opendeviationbar.conf" /etc/monit/conf.d/opendeviationbar.conf
chmod 644 /etc/monit/conf.d/opendeviationbar.conf
echo "Copied opendeviationbar.conf → /etc/monit/conf.d/"

echo "=== Deploying alert scripts ==="
cp "${MONIT_DIR}/obdpy-monit-alert.sh" /usr/local/bin/obdpy-monit-alert.sh
chmod 755 /usr/local/bin/obdpy-monit-alert.sh
echo "Copied obdpy-monit-alert.sh → /usr/local/bin/"

cp "${MONIT_DIR}/obdpy-check-heartbeat-timer.sh" /usr/local/bin/obdpy-check-heartbeat-timer.sh
chmod 755 /usr/local/bin/obdpy-check-heartbeat-timer.sh
echo "Copied obdpy-check-heartbeat-timer.sh → /usr/local/bin/"

echo "=== Securing monitrc ==="
chmod 700 /etc/monit/monitrc

echo "=== Validating config ==="
if monit -t; then
    echo "Config syntax OK"
else
    echo "ERROR: monit config validation failed" >&2
    exit 1
fi

echo "=== Enabling and restarting monit ==="
systemctl enable monit
systemctl restart monit

echo "=== Verifying ==="
sleep 2
monit status | head -20

echo ""
echo "=== Deploy complete ==="
echo "  Web UI: http://localhost:2812 (if httpd configured in monitrc)"
echo "  Status: sudo monit status"
echo "  Logs:   /var/log/monit.log"
