Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env bash
- set -Eeuo pipefail
- readonly ENV_FILE="/etc/pi-heartbeat.env"
- readonly SERVICE_FILE="/etc/systemd/system/pi-heartbeat.service"
- readonly TIMER_FILE="/etc/systemd/system/pi-heartbeat.timer"
- usage() {
- cat <<'EOF'
- Usage:
- sudo ./install-heartbeat.sh <ping-url>
- Example:
- sudo ./install-heartbeat.sh https://hc-ping.com/your-check-uuid
- EOF
- }
- if [[ ${EUID} -ne 0 ]]; then
- echo "Error: run this installer with sudo." >&2
- usage >&2
- exit 1
- fi
- if [[ $# -ne 1 ]]; then
- usage >&2
- exit 1
- fi
- ping_url=$1
- case "$ping_url" in
- https://* | http://*) ;;
- *)
- echo "Error: ping URL must begin with https:// or http://." >&2
- exit 1
- ;;
- esac
- if [[ "$ping_url" == *$'\n'* || "$ping_url" == *$'\r'* || "$ping_url" == *' '* ]]; then
- echo "Error: ping URL contains invalid whitespace." >&2
- exit 1
- fi
- if ! command -v systemctl >/dev/null 2>&1; then
- echo "Error: systemd is required." >&2
- exit 1
- fi
- if ! command -v curl >/dev/null 2>&1; then
- echo "curl is missing; installing it..."
- apt-get update -qq
- apt-get install -y curl
- fi
- umask 077
- printf 'PING_URL=%s\n' "$ping_url" >"$ENV_FILE"
- chown root:root "$ENV_FILE"
- chmod 0600 "$ENV_FILE"
- cat >"$SERVICE_FILE" <<'EOF'
- [Unit]
- Description=External availability heartbeat
- Wants=network-online.target
- After=network-online.target
- [Service]
- Type=oneshot
- EnvironmentFile=/etc/pi-heartbeat.env
- ExecStart=/usr/bin/curl --fail --silent --show-error --max-time 10 --retry 2 --retry-delay 3 ${PING_URL}
- TimeoutStartSec=45
- NoNewPrivileges=true
- PrivateTmp=true
- ProtectHome=true
- ProtectSystem=strict
- EOF
- cat >"$TIMER_FILE" <<'EOF'
- [Unit]
- Description=Send external availability heartbeat every minute
- [Timer]
- OnBootSec=2min
- OnUnitActiveSec=1min
- AccuracySec=10s
- RandomizedDelaySec=10s
- Unit=pi-heartbeat.service
- [Install]
- WantedBy=timers.target
- EOF
- chown root:root "$SERVICE_FILE" "$TIMER_FILE"
- chmod 0644 "$SERVICE_FILE" "$TIMER_FILE"
- systemctl daemon-reload
- systemctl enable --now pi-heartbeat.timer
- echo "Sending the first heartbeat..."
- if systemctl start pi-heartbeat.service; then
- echo "Heartbeat installed and first check-in succeeded."
- echo "Timer status:"
- systemctl --no-pager --full status pi-heartbeat.timer || true
- else
- echo "Heartbeat was installed, but the first check-in failed." >&2
- echo "Inspect it with: journalctl -u pi-heartbeat.service -n 30 --no-pager" >&2
- exit 1
- fi
Advertisement
Add Comment
Please, Sign In to add comment