#!/bin/bash
# Mirror replication check with email alert
# Runs on mirror (46.225.155.116) via cron

LOG="/var/log/mirror-sync/check-replication.log"
ALERT_EMAIL="katlun@gmail.com"

STATUS=$(docker exec accounting-accounting-db-1 psql -U accounting -d windyview_accounting -tAc "SELECT status FROM pg_stat_wal_receiver;" 2>/dev/null | tr -d '[:space:]')
LAG=$(docker exec accounting-accounting-db-1 psql -U accounting -d windyview_accounting -tAc "SELECT COALESCE(pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()), 0);" 2>/dev/null | tr -d '[:space:]')

if [ "$STATUS" = "streaming" ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] OK: byte_lag=${LAG:-0} status=${STATUS}" >> "$LOG"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] FAIL: status=${STATUS:-unknown} lag=${LAG:-unknown}" >> "$LOG"

    ssh -o ConnectTimeout=5 root@91.98.164.18 "docker exec mailcowdockerized-postfix-mailcow-1 sh -c \"printf 'Subject: [ALERT] Mirror replication FAILED\nFrom: noreply@windyviews.com\nTo: ${ALERT_EMAIL}\nContent-Type: text/plain; charset=utf-8\n\nMirror DB replication is DOWN.\n\nStatus: ${STATUS:-unknown}\nLag: ${LAG:-unknown}\nTimestamp: $(date)\nServer: mirror (46.225.155.116)\n' | /usr/sbin/sendmail -f noreply@windyviews.com ${ALERT_EMAIL}\"" 2>/dev/null
fi
