# syntax=docker/dockerfile:1
FROM rust:latest as rust-build
WORKDIR /build
COPY ./markdown_backend ./markdown_backend
WORKDIR /build/markdown_backend
RUN rustup target add x86_64-unknown-linux-musl
RUN apt-get update && apt-get install -y musl-tools
# Build with musl target for static linking
RUN cargo build --release --target x86_64-unknown-linux-musl

FROM node:20

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .
# Ensure posts directory exists and has correct permissions
RUN mkdir -p /app/posts
COPY posts/* /app/posts/
RUN chmod -R 755 /app/posts

# Copy the statically linked Rust binary from the build stage
COPY --from=rust-build /build/markdown_backend/target/x86_64-unknown-linux-musl/release/markdown_backend ./markdown_backend/target/release/markdown_backend
RUN chmod +x ./markdown_backend/target/release/markdown_backend

RUN npm run build

# Create and set permissions for the docker volume mount point
RUN mkdir -p /app/docker && chmod 777 /app/docker


# Set environment variable to indicate we're running in Docker
ENV DOCKER_CONTAINER=true

VOLUME ["/app/docker"]

EXPOSE 3000

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

CMD ["npm", "start"]

# Building Instructions
#
# docker build -t markdownblog .
# docker run -p 8080:3000 -v markdownblog-posts:/app/docker markdownblog
# docker container prune