#!/bin/sh

set -eu

STATE_DIR=/var/lib/wedesk
UDP_PORT_RANGE=21120:21139

ufw_enabled() {
    command -v ufw >/dev/null 2>&1 \
        && grep -Eq '^[[:space:]]*ENABLED=yes' /etc/ufw/ufw.conf 2>/dev/null
}

firewalld_enabled() {
    command -v firewall-cmd >/dev/null 2>&1 \
        && firewall-cmd --state >/dev/null 2>&1
}

configure_firewall() {
    mkdir -p "$STATE_DIR"
    firewall_active=false
    firewall_ready=true

    if ufw_enabled; then
        firewall_active=true
        if ! ufw status | grep -Fq "$UDP_PORT_RANGE/udp"; then
            if ufw allow "$UDP_PORT_RANGE/udp" comment 'SoonDesk P2P'; then
                touch "$STATE_DIR/ufw-p2p-rule-managed"
            else
                firewall_ready=false
            fi
        fi
    fi

    if firewalld_enabled; then
        firewall_active=true
        if ! firewall-cmd --permanent --query-port="$UDP_PORT_RANGE/udp" >/dev/null 2>&1; then
            if firewall-cmd --permanent --add-port="$UDP_PORT_RANGE/udp" >/dev/null \
                && firewall-cmd --reload >/dev/null; then
                touch "$STATE_DIR/firewalld-p2p-rule-managed"
            else
                firewall_ready=false
            fi
        fi
    fi

    rm -f "$STATE_DIR/p2p-firewall-ready" "$STATE_DIR/p2p-firewall-not-active"
    if [ "$firewall_ready" = true ]; then
        touch "$STATE_DIR/p2p-firewall-ready"
        if [ "$firewall_active" = false ]; then
            touch "$STATE_DIR/p2p-firewall-not-active"
        fi
        chmod 0644 "$STATE_DIR"/p2p-firewall-* 2>/dev/null || true
        echo "SoonDesk P2P UDP $UDP_PORT_RANGE is ready"
        return 0
    fi

    echo "SoonDesk: unable to configure P2P UDP $UDP_PORT_RANGE" >&2
    return 1
}

firewall_status() {
    if [ -f "$STATE_DIR/p2p-firewall-ready" ]; then
        if [ -f "$STATE_DIR/p2p-firewall-not-active" ]; then
            echo "inactive"
        else
            echo "ready"
        fi
        return 0
    fi
    if ufw_enabled || firewalld_enabled; then
        echo "blocked"
        return 1
    fi
    echo "inactive"
    return 0
}

case "${1:-status}" in
    configure)
        configure_firewall
        ;;
    status)
        firewall_status
        ;;
    *)
        echo "Usage: $0 {configure|status}" >&2
        exit 2
        ;;
esac
