FROM golang:1.19-alpine as builder

# Install build dependencies
RUN apk add alpine-sdk

# Create appuser.
ENV USER=appuser
ENV UID=10001

# See https://stackoverflow.com/a/55757473/12429735
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    "${USER}"

# Prepare dependencies
RUN mkdir /build
ADD go.mod go.sum /build/
WORKDIR /build
RUN go mod download
RUN go mod verify

# Prepare app
ADD server.go /build/
# Build as static binary
RUN CGO_ENABLED=1 go build --tags "fts5" -ldflags='-w -s -extldflags "-static"' -o /build/search-server

# Copy binary to empty image
FROM scratch
# Import the user and group files from the builder.
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/group /etc/group

# Prepare environment
ENV GIN_MODE=release

# Copy executable
COPY  --from=builder /build/search-server /server

# Use an unprivileged user.
USER appuser:appuser

ENTRYPOINT ["/server"]