# Build stage
FROM golang:bullseye AS base

RUN adduser \
  --disabled-password \
  --gecos "" \
  --home "/nonexistent" \
  --shell "/sbin/nologin" \
  --no-create-home \
  --uid 65532 \
  small-user

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download

COPY sqlite-latest.sqlite ./
COPY . .

RUN apt-get update && apt-get install -y \
    gcc \
    libc6-dev

RUN CGO_ENABLED=1 \
        GOOS=linux \
        GOARCH=amd64 \
        CGO_LDFLAGS="-static -w -s" \
        go build \
        -ldflags '-extldflags "-static"' \
        -o zkill-susser \
        .

# Final stage
FROM alpine:latest
RUN apk add --no-cache libc6-compat

# Copy the binary from the build stage
COPY --from=base /app/zkill-susser /zkill-susser

# Copy necessary files from the build stage
COPY --from=base /usr/share/zoneinfo /usr/share/zoneinfo
COPY --from=base /etc/passwd /etc/passwd
COPY --from=base /etc/group /etc/group

# Copy SQLite database file
COPY --from=base /app/sqlite-latest.sqlite /sqlite-latest.sqlite

# Create data directory and set permissions
RUN mkdir -p /data && chown small-user:small-user /data

# Use the non-root user
USER small-user

EXPOSE 3000

ENV PORT=3000

CMD ["/zkill-susser", "-server", "-port", "3000"]
