#!/bin/sh
# systemd generator for clamav-daemon.socket
# This generator reads /etc/clamav/clamd.conf and generates appropriate
# socket configuration based on whether TCP or Unix socket is configured.
#
# This ensures the systemd socket unit stays in sync with clamd.conf
# when the configuration is changed via dpkg-reconfigure or manual editing.

set -e

CLAMAV_CONF="/etc/clamav/clamd.conf"
GENERATOR_DIR="$1"
SOCKET_DROP_IN_DIR="${GENERATOR_DIR}/clamav-daemon.socket.d"

# Exit if clamd.conf doesn't exist
if [ ! -f "$CLAMAV_CONF" ]; then
    exit 0
fi

# Parse clamd.conf to extract socket configuration
# We need to handle both TCPSocket and LocalSocket directives

# Read configuration file
while IFS= read -r line; do
    # Skip comments and empty lines
    case "$line" in
        \#*|"") continue ;;
    esac

    # Extract first word (directive) and value
    directive=$(echo "$line" | awk '{print $1}')
    value=$(echo "$line" | awk '{print $2}')

    case "$directive" in
        TCPSocket)
            tcp_socket="$value"
            ;;
        TCPAddr)
            tcp_addr="$value"
            ;;
        LocalSocket)
            listen_stream_local="ListenStream=${value}"
            ;;
        LocalSocketMode)
            local_socket_mode="SocketMode=${value}"
            ;;
        LocalSocketGroup)
            local_socket_group="SocketGroup=${value}"
            ;;
    esac
done < "$CLAMAV_CONF"

if [ -n "$tcp_socket" ]; then
    # Add TCP socket with optional address
    if [ -n "$tcp_addr" ] && [ "$tcp_addr" != "any" ]; then
        case "$tcp_addr" in
            *:*)
                listen_stream_tcp="ListenStream=[${tcp_addr}]:${tcp_socket}"
                ;;
            *)
                listen_stream_tcp="ListenStream=${tcp_addr}:${tcp_socket}"
                ;;
        esac
    else
        listen_stream_tcp="ListenStream=${tcp_socket}"
    fi
fi

# Generate socket configuration
if [ -n "$listen_stream_local" ] || [ -n "$listen_stream_tcp" ]; then
    # Create drop-in directory
    mkdir -p "$SOCKET_DROP_IN_DIR"
    cat > "${SOCKET_DROP_IN_DIR}/listen.conf" << EOF
# Automatically generated by clamav-daemon-socket-generator
# Based on configuration in ${CLAMAV_CONF}
[Socket]
# Clear any existing ListenStream directives
ListenStream=
${listen_stream_tcp}
${listen_stream_local}
${local_socket_mode}
${local_socket_group}
EOF
fi

exit 0
