#! /bin/bash
#
# Opens a single ufw rule for HP network printer/scanner discovery: either
# mDNS (UDP 5353, multicast group 224.0.0.251) or SLP (UDP 427, multicast
# group 224.0.1.60). mDNS and SLP are independent protocols/settings --
# call this once per port you want opened. No-op if ufw is absent or
# inactive, since a disabled firewall already permits this traffic.
#
# Usage: init-ufw-firewall <5353|427>
#
# Prints ADDED:<port> or PREEXISTING:<port> on stdout so the caller can
# tell whether HPLIP added the rule or it already existed beforehand --
# used to decide what's safe to revert on uninstall.

port="$1"

if ! command -v ufw >/dev/null 2>&1; then
    exit 0
fi

ufw status | grep -q "^Status: active"
if [ $? -ne 0 ]; then
    exit 0
fi

case "$port" in
    5353)
        mcast=224.0.0.251
        comment='hplip mDNS discovery'
        ;;
    427)
        mcast=224.0.1.60
        comment='hplip SLP discovery'
        ;;
    *)
        exit 0
        ;;
esac

ufw status | grep "$mcast" | grep -q "$port/udp"
if [ $? -eq 0 ]; then
    echo "PREEXISTING:$port"
else
    ufw allow proto udp from any to $mcast port $port comment "$comment" >/dev/null 2>&1
    echo "ADDED:$port"
fi

exit 0
