FROM rust:1.86.0-bookworm AS builder

# Install cargo-binstall, which makes it easier to install other
# cargo extensions like cargo-leptos
# (uname -m gives x86_64 or aarch64, so the image builds on both architectures)
RUN wget https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-$(uname -m)-unknown-linux-musl.tgz \
  && tar -xvf cargo-binstall-$(uname -m)-unknown-linux-musl.tgz \
  && cp cargo-binstall /usr/local/cargo/bin

# Install required tools
RUN apt-get update -y \
  && apt-get install -y --no-install-recommends clang

# Install cargo-leptos
RUN cargo binstall cargo-leptos -y

RUN rustup default stable

# Add the WASM target
RUN rustup target add wasm32-unknown-unknown
#RUN rustup target add wasm32-unknown-unknown --toolchain nightly


# Make an /app dir, which everything will eventually live in
RUN mkdir -p /app
WORKDIR /app
COPY . .

# Build the app
#RUN cargo leptos build --release -vv
RUN LEPTOS_OUTPUT_NAME="rezervator-$(tr -dc a-z0-9 </dev/urandom | head -c 10)" cargo leptos build -r -P

FROM debian:bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update -y \
  && apt-get install -y --no-install-recommends openssl ca-certificates \
  && apt-get autoremove -y \
  && apt-get clean -y \
  && rm -rf /var/lib/apt/lists/*

# Copy the server binary to the /app directory
COPY --from=builder /app/target/release/rezervator /app/

# /target/site contains our JS/WASM/CSS, etc.
COPY --from=builder /app/target/site /app/target/site

# Set any required env variables and
EXPOSE 3000

# The config file holds passwords and the session key. Mount it to /app/config, never under
# /app/target/site, which is served as static files.
RUN mkdir -p /app/config
VOLUME /app/config

# Uploaded banner. Keep this volume when the container is replaced.
RUN mkdir -p /app/data
VOLUME /app/data

# Healthy when the server answers and can reach its database.
# (No --start-interval: it needs Docker 25, and deploy/rezervator.sh probes on its own.)
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
  CMD ["/app/rezervator", "-c", "/app/config/config.toml", "--healthcheck"]

# Run the server
CMD ["/app/rezervator", "-c", "/app/config/config.toml"]