# Base: Debian 12 + .NET SDK 8.0
FROM mcr.microsoft.com/dotnet/sdk:8.0

# Deps and .NET runtime
RUN apt-get update && apt-get install -y --no-install-recommends \
        wget gnupg ca-certificates apt-transport-https && \
    wget https://packages.microsoft.com/config/debian/12/packages-microsoft-prod.deb && \
    dpkg -i packages-microsoft-prod.deb && \
    rm packages-microsoft-prod.deb && \
    apt-get update && apt-get install -y --no-install-recommends \
        dotnet-runtime-8.0 bash libcap2-bin sqlite3 libsqlite3-dev libpam0g && \
    rm -rf /var/lib/apt/lists/*

# Fake systemctl to placate maintainer scripts
RUN ln -s /bin/true /usr/local/bin/systemctl

# Download and install CompleteFTP trial
ARG COMPLETEFTP_DEB_URL=https://enterprisedt.com/products/completeftp/download/completeftp.deb
RUN apt-get update && apt-get install -y --no-install-recommends sudo && \
    wget -O /tmp/completeftp.deb "$COMPLETEFTP_DEB_URL" && \
    dpkg -i /tmp/completeftp.deb || true && \
    apt-get install -y -f && \
    rm -rf /var/lib/apt/lists/*

# Stable machine-id for licensing
RUN set -eux; \
    mkdir -p /var/lib/dbus; \
    if [ ! -s /etc/machine-id ]; then \
        cat /proc/sys/kernel/random/uuid | tr -d '-' > /etc/machine-id; \
    fi; \
    ln -sf /etc/machine-id /var/lib/dbus/machine-id; \
    chmod 444 /etc/machine-id

# Clean temp and fake systemctl
RUN rm -f /tmp/completeftp.deb /usr/local/bin/systemctl

# Ensure CLI on PATH
RUN if [ ! -e /usr/bin/completeftp ] && [ -x /usr/lib/completeftp/bin/completeftp ]; then \
        ln -s /usr/lib/completeftp/bin/completeftp /usr/bin/completeftp; \
    fi

# Preserve pristine defaults for first-run seeding
RUN mkdir -p /opt/completeftp-seed && \
    cp -a /var/lib/completeftp/. /opt/completeftp-seed/

# Install gosu for privilege de-escalation
RUN apt-get update && apt-get install -y --no-install-recommends gosu && \
    rm -rf /var/lib/apt/lists/*

EXPOSE 21 22 990 80 443

# Create service user if missing
RUN id -u completeftp 2>/dev/null || \
    useradd -r -u 270 -g nogroup -d /usr/lib/completeftp -s /usr/sbin/nologin completeftp

# Entrypoint handles first-run seeding and privilege drop
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

USER root
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD ["/usr/bin/completeftp", "run", "--enable-uds"]
