#!/bin/sh
PATH=/usr/sbin:/usr/bin:/sbin:/bin

APP_SERVICE=nyq-appliance
IF=eth0
LOCK=/var/run/recover_multicast_network.lock

# avoid duplicate runs
if [ -e "$LOCK" ]; then
    exit 0
fi
touch "$LOCK"
trap 'rm -f "$LOCK"' EXIT

logger -t nyq-recovery "multicast recovery starting"

# stop appliance first so it does not race network recovery
systemctl stop "$APP_SERVICE" 2>/dev/null || service "$APP_SERVICE" stop 2>/dev/null || true

# restart networking
systemctl restart networking 2>/dev/null || service networking restart 2>/dev/null || true

# wait for interface to be truly back
for i in $(seq 1 30); do
    CARRIER=$(cat /sys/class/net/$IF/carrier 2>/dev/null)
    if [ "$CARRIER" = "1" ] && ip -4 addr show dev "$IF" | grep -q "inet "; then
        break
    fi
    sleep 1
done

# optional extra settle time
sleep 2

# now restart appliance
systemctl start "$APP_SERVICE" 2>/dev/null || service "$APP_SERVICE" start 2>/dev/null || true

logger -t nyq-recovery "multicast recovery complete"