# syntax=docker/dockerfile:1

############################
# Build stage
############################
FROM golang:1.24-alpine AS builder

# You can still override these if you want
ARG TAILWIND_VERSION=v4.1.11

# deps for CGO + curl
RUN apk add --no-cache git build-base sqlite-dev curl

WORKDIR /app

# Cache go deps
COPY go.mod go.sum ./
RUN go mod download

# ---- templ CLI: install the SAME version as in go.mod ----
# Read the templ module version from go.mod, then install matching CLI
RUN set -eux; \
    TEMPL_VER="$(go list -m -f '{{.Version}}' github.com/a-h/templ)"; \
    echo "Installing templ CLI @$TEMPL_VER"; \
    go install "github.com/a-h/templ/cmd/templ@${TEMPL_VER}"

# ---- Tailwind v4 standalone ----
RUN set -eux; \
    ARCH="$(uname -m)"; \
    case "${ARCH}" in \
    x86_64) TAILWIND_ARCH="x64" ;; \
    aarch64) TAILWIND_ARCH="arm64" ;; \
    *) echo "Unsupported architecture: ${ARCH}" && exit 1 ;; \
    esac; \
    TAILWIND_URL="https://github.com/tailwindlabs/tailwindcss/releases/download/${TAILWIND_VERSION}/tailwindcss-linux-${TAILWIND_ARCH}-musl"; \
    echo "Downloading Tailwind CSS for ${ARCH} from ${TAILWIND_URL}"; \
    curl -fsSL -o /usr/local/bin/tailwindcss "${TAILWIND_URL}"; \
    # Verify the download is a valid ELF binary \
    file /usr/local/bin/tailwindcss | grep -q "ELF.*executable" || (echo "Downloaded file is not a valid ELF binary:" && file /usr/local/bin/tailwindcss && exit 1); \
    chmod +x /usr/local/bin/tailwindcss; \
    # Test that the binary works \
    /usr/local/bin/tailwindcss --version

# App source
COPY . .

# 1) Generate templ -> .go (now CLI matches module, so parsing works)
RUN templ generate

# 2) Build Tailwind (v4) – no --clean in v4
RUN mkdir -p ./web/static/css
RUN tailwindcss -i ./web/resources/css/input.css -o ./web/static/css/output.css --minify

# 3) Build Go binary (CGO for SQLite)
ENV CGO_ENABLED=1
RUN go build -ldflags="-s -w" -o /app/maot-shortner ./cmd/maot-shortner

############################
# Runtime stage
############################
FROM alpine:3.20

RUN apk add --no-cache ca-certificates sqlite-libs

WORKDIR /app

COPY --from=builder /app/maot-shortner .
COPY --from=builder /app/web/static ./web/static

RUN mkdir -p /app/data

EXPOSE 3032
ENV DATABASE_PATH=/app/data/shortener.db
VOLUME ["/app/data"]

CMD ["./maot-shortner"]
