# Stage 1: Build stage
# Using the Golang docker image specifically for Alpine. Necessary because Alpine Linux uses musl instead of glibc, making binaries compiled dynamically using glibc incompatible with Alpine. 
FROM golang:1.23.9-alpine3.21 AS build

# Install build dependencies
RUN apk add --no-cache git

# Set working directory
WORKDIR /app

# Clone the Beetroot repository
RUN git clone https://github.com/skandix/Beetroot.git .

# Change directory so that we can build the program.
WORKDIR /app/cmd/beetroot

# Downloads any Go module dependencies defined in the source code.
RUN go get
# Build beetroot as a Go binary
RUN go build -o beetroot main.go
RUN mv beetroot /app

# Stage 2: Runtime stage
FROM alpine:3.21

# Open the port 8080, so that Beetroot can listen through it.
EXPOSE 8080

# Add support for timezone
RUN apk add --no-cache tzdata

# Install curl for testing
RUN apk add --no-cache curl

# Create a non-root user to run the application, naming it 'beetroot'.
RUN adduser -D beetroot

# Set env variable for timezone
ENV TZ=UTC

# Set working directory
WORKDIR /app

# Copy the compiled binary from the build stage
COPY --from=build /app/beetroot /app/

# Change ownership to non-root user
RUN chown -R beetroot:beetroot /app

# Switch to non-root user
USER beetroot

# Run beetroot when the container starts
CMD ["/app/beetroot"]
