#!/bin/bash
ALLOW=${ALLOW:-192.168.0.0/16 172.16.0.0/12}
OWNER=${OWNER:-nobody}
GROUP=${GROUP:-nogroup}

if [ "${GROUP}" != "nogroup" ]; then
    groupadd -g "${GROUP}" rsyncdgroup 2>/dev/null
fi
if [ "${OWNER}" != "nobody" ]; then
    useradd -u "${OWNER}" -G rsyncdgroup rsyncduser 2>/dev/null
fi

if [ ! -f /etc/rsyncd.conf ]; then
    cat <<EOF > /etc/rsyncd.conf
uid = ${OWNER}
gid = ${GROUP}
use chroot = yes
pid file = /var/run/rsyncd.pid
log file = /dev/stdout
EOF

    # multi-module mode: MODULE_1_NAME, MODULE_1_PATH, MODULE_1_ALLOW, ...
    i=1
    while true; do
        name_var="MODULE_${i}_NAME"
        path_var="MODULE_${i}_PATH"
        allow_var="MODULE_${i}_ALLOW"
        name="${!name_var}"
        [ -z "${name}" ] && break
        path="${!path_var:-/volume_${i}}"
        allow="${!allow_var:-${ALLOW}}"
        cat <<EOF >> /etc/rsyncd.conf

[${name}]
    hosts deny = *
    hosts allow = ${allow}
    read only = false
    path = ${path}
    comment = ${name}
EOF
        i=$((i + 1))
    done

    # single-module fallback: VOLUME env var
    if [ "${i}" -eq 1 ]; then
        VOLUME=${VOLUME:-volume}
        cat <<EOF >> /etc/rsyncd.conf

[${VOLUME}]
    hosts deny = *
    hosts allow = ${ALLOW}
    read only = false
    path = /volume
    comment = ${VOLUME}
EOF
    fi
fi

exec /usr/bin/rsync --no-detach --daemon --config /etc/rsyncd.conf "$@"
