# Start from the latest golang base image
FROM golang:1.24-alpine AS builder

WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-w -s" -trimpath -o main .

# Start a new stage from alpine:latest
FROM alpine:latest  AS runner

ARG POSTGRES_USER
ARG POSTGRES_PASSWORD
ARG POSTGRES_DB
ARG PGHOST
ARG PGPORT
ARG IMAGEOPTION
ARG CONCURRENT_IMAGES
ARG STORAGE_URL
ARG STORAGE_TOKEN

RUN apk add --no-cache ca-certificates ffmpeg curl libwebp-tools

ENV GOMEMLIMIT=2750MiB
ENV GOGC=100
ENV PGHOST=$PGHOST
ENV POSTGRES_DB=$POSTGRES_DB
ENV PGPORT=$PGPORT
ENV POSTGRES_USER=$POSTGRES_USER
ENV POSTGRES_PASSWORD=$POSTGRES_PASSWORD
ENV IMAGEOPTION=$IMAGEOPTION
ENV CONCURRENT_IMAGES=$CONCURRENT_IMAGES
ENV STORAGE_URL=$STORAGE_URL
ENV STORAGE_TOKEN=$STORAGE_TOKEN

WORKDIR /app

# Copy the Pre-built binary file from the previous stage
COPY --from=builder /app/main /app/.
COPY ./test.jpg /app/test.jpg
COPY ./scripts /app/scripts
COPY ./categorie.xml /app/categorie.xml
COPY ./caratteristiche.xml /app/caratteristiche.xml
RUN chmod +x /app/scripts/*.sh

RUN mkdir -p /app/.bin/webp \
    && ln -s /usr/bin/cwebp /app/.bin/webp/cwebp \
    && ln -s /usr/bin/dwebp /app/.bin/webp/dwebp \
    && ln -s /usr/bin/gif2webp /app/.bin/webp/gif2webp \
    && ln -s /usr/bin/img2webp /app/.bin/webp/img2webp \
    && ln -s /usr/bin/webpmux /app/.bin/webp/webpmux

RUN mkdir -p images videos failed_requests

# Expose port 1323 to the outside world
EXPOSE 1323

# Command to run the executable
CMD ["./main"]
