##################
### BASE STAGE ###
##################
FROM rust:1.94.0 AS base

RUN rustup target add wasm32-unknown-unknown
RUN rustup target add x86_64-unknown-linux-musl

# Install build dependencies
RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
RUN cargo install --locked strip_cargo_version@0.0.3
RUN cargo binstall wasm-pack@0.13.1

# required by "ring"
RUN apt-get update && apt-get install -y musl-tools

WORKDIR /app
RUN mkdir gui srv lib

###########################
### STRIP-VERSION STAGE ###
###########################
FROM base AS strip-version

COPY Cargo.lock Cargo.toml ./
COPY ./gui/Cargo.toml ./gui/
COPY ./srv/Cargo.toml ./srv/
COPY ./lib/Cargo.toml ./lib/
RUN strip_cargo_version

###################
### BUILD STAGE ###
###################
FROM base AS build

RUN cargo init --lib gui
RUN cargo init --bin srv
RUN cargo init --lib lib

COPY --from=strip-version /app/gui/Cargo.toml /app/gui/
COPY --from=strip-version /app/srv/Cargo.toml /app/srv/
COPY --from=strip-version /app/lib/Cargo.toml /app/lib/
COPY --from=strip-version /app/Cargo.toml /app/Cargo.lock /app/

# Compile dependencies first, so that they are cached by Docker
WORKDIR /app/srv
RUN cargo build --release --target x86_64-unknown-linux-musl
WORKDIR /app/gui
RUN cargo build --release --target wasm32-unknown-unknown

WORKDIR /app
COPY . .

WORKDIR /app/srv
RUN cargo build --release --target x86_64-unknown-linux-musl
RUN strip /app/target/x86_64-unknown-linux-musl/release/inkopslista-srv
WORKDIR /app/gui
RUN wasm-pack build --release --target web

########################
### PRODUCTION STAGE ###
########################
FROM scratch

ENV RUST_LOG="info"
ENV ROCKET_ADDRESS="0.0.0.0"
ENV ROCKET_PORT="8000"

VOLUME ["/data"]
ENV DB_PATH="/data/db.sqlite"

WORKDIR /

# Copy application binary
COPY --from=build /app/target/x86_64-unknown-linux-musl/release/inkopslista-srv /
# Copy web bundle
COPY --from=build /app/gui/index.html /www/index.html
COPY --from=build /app/gui/pkg        /www/pkg

CMD ["/inkopslista-srv"]
