# Stage 1: Build the application
# Use a specific Rust version for reproducibility, slim variant for smaller base
FROM rust:1.88-slim-bookworm AS builder
LABEL maintainer="Quintus Leung"

# Install system dependencies if needed by any crates (e.g., libssl-dev, pkg-config for TLS/crypto)
RUN apt-get update && apt-get install -y libssl-dev pkg-config libpam0g-dev

WORKDIR /app

# Copy manifests
COPY Cargo.toml Cargo.lock ./

# Create dummy main.rs to build dependencies
RUN mkdir src && \
    echo "fn main() {println!(\"if you see this, the build broke\")}" > src/main.rs

# Build dependencies - this will be cached
RUN cargo build --release --locked

# Remove dummy main.rs
RUN rm src/main.rs

# Copy source code
COPY src ./src

# Touch main.rs to force rebuild of the app
RUN touch src/main.rs

# Build the application in release mode
RUN cargo build --release --locked

# Stage 2: Create the final lightweight image
FROM debian:bookworm-slim AS runner

# Install runtime dependencies
RUN apt-get update && apt-get install -y libssl3 libpam0g && rm -rf /var/lib/apt/lists/*

# Arguments for user/group creation, can be overridden at build time
ARG UID=1001
ARG GID=1001

# Create a non-root user and group for security
RUN groupadd -g ${GID} appgroup && \
    useradd -u ${UID} -g appgroup -ms /bin/bash -d /app appuser

WORKDIR /app

# Copy the compiled binary from the builder stage to a common bin location
COPY --from=builder /app/target/release/rust-socksd /usr/local/bin/rust-socksd

# Ensure the binary is executable
RUN chmod +x /usr/local/bin/rust-socksd

# Expose the default SOCKS5, HTTP, and Admin ports
EXPOSE 1080
EXPOSE 8080
EXPOSE 8081

# Switch to the non-root user
USER appuser

# Set default environment variables for rust-socksd configuration.
# Assumes rust-socksd reads these.

# Listen on all interfaces inside the container
ENV RUST_SOCKSD_BIND_ADDRESS="0.0.0.0"
# Default SOCKS5 port
ENV RUST_SOCKSD_SOCKS5_PORT="1080"
# Default HTTP port
ENV RUST_SOCKSD_HTTP_PORT="8080"
# Default Admin port
ENV RUST_SOCKSD_ADMIN_PORT="8081"
# Admin server enabled status
ENV RUST_SOCKSD_ADMIN_ENABLED="false"
# Log level
ENV RUST_SOCKSD_LOG_LEVEL="info"

# Default command to run the application
ENTRYPOINT ["/usr/local/bin/rust-socksd"]
