# Using multistage build: 
# 	https://docs.docker.com/develop/develop-images/multistage-build/
# 	https://whitfin.io/speeding-up-rust-docker-builds/
####################### VAULT BUILD IMAGE  #######################
FROM alpine as vault

ENV VAULT_VERSION "v2.9.0"

ENV URL "https://github.com/dani-garcia/bw_web_builds/releases/download/$VAULT_VERSION/bw_web_$VAULT_VERSION.tar.gz"

RUN apk add --update-cache --upgrade \
    curl \
    tar

RUN mkdir /web-vault
WORKDIR /web-vault

RUN curl -L $URL | tar xz
RUN ls


########################## BUILD IMAGE  ##########################
# We need to use the Rust build image, because
# we need the Rust compiler and Cargo tooling
FROM rust as build

# Using bundled SQLite, no need to install it
# RUN apt-get update && apt-get install -y\
#    sqlite3\
#    --no-install-recommends\
# && rm -rf /var/lib/apt/lists/*

# Creates a dummy project used to grab dependencies
RUN USER=root cargo new --bin app
WORKDIR /app

# Copies over *only* your manifests and build files
COPY git/Cargo.* ./
COPY git/rust-toolchain ./rust-toolchain
COPY git/build.rs ./build.rs

# Builds your dependencies and removes the
# dummy project, except the target folder
# This folder contains the compiled dependencies
RUN cargo build --release
RUN find . -not -path "./target*" -delete

# Copies the complete project
# To avoid copying unneeded files, use .dockerignore
COPY git .

# Make sure that we actually build the project
RUN touch src/main.rs

# Builds again, this time it'll just be
# your actual source files being built
RUN cargo build --release

######################## PACKAGING IMAGE  ########################
# Create a new stage with a minimal image
# because we already have a binary built
FROM debian:stretch-slim

# Create package directory
RUN mkdir -p /bitwarden_package/DEBIAN
RUN mkdir -p /bitwarden_package/usr/local/bin
RUN mkdir -p /bitwarden_package/usr/lib/systemd/system
RUN mkdir -p /bitwarden_package/etc/bitwarden_rs
RUN mkdir -p /bitwarden_package/usr/share/bitwarden_rs

WORKDIR /bitwarden_package

# Copies the files from the context (Rocket.toml file and web-vault)
# and the binary from the "build" stage to the current stage
COPY debian/control /bitwarden_package/DEBIAN/control
COPY debian/postinst /bitwarden_package/DEBIAN/postinst
COPY debian/conffiles /bitwarden_package/DEBIAN/conffiles
COPY git/Rocket.toml /bitwarden_package/etc/bitwarden_rs
COPY debian/config.env /bitwarden_package/etc/bitwarden_rs
COPY debian/bitwarden_rs.service /bitwarden_package/usr/lib/systemd/system
COPY --from=vault /web-vault /bitwarden_package/usr/share/bitwarden_rs/web-vault
COPY --from=build app/target/release/bitwarden_rs /bitwarden_package/usr/local/bin

# Create the package
RUN dpkg-deb --build . bitwarden-rs.deb