# Stage 1: Build the Go application
FROM golang:1.26.2-alpine3.23@sha256:f85330846cde1e57ca9ec309382da3b8e6ae3ab943d2739500e08c86393a21b1 AS builder

WORKDIR /app

# Download and verify dependencies before copying the application source.
COPY go.mod go.sum ./
RUN go mod download && go mod verify

# Copy the rest of the application source code
COPY . .

# Build the Go application
# The binary will be named 'app'
RUN go build -v -o /app/main main.go

# Stage 2: Create the final image
FROM alpine:3.22@sha256:14358309a308569c32bdc37e2e0e9694be33a9d99e68afb0f5ff33cc1f695dce

# Install Terraform CLI and other utilities.
ARG TERRAFORM_VERSION=1.15.8
ARG TERRAFORM_SHA256=d25ce7b6902013ad905db3d2eab0be4cd905887fe88b81a6171b8d5503c31f3d
RUN apk add --no-cache wget unzip ca-certificates git openssh-client make

# Install Terraform from its checksummed release archive.
RUN wget -q https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip && \
    echo "${TERRAFORM_SHA256}  terraform_${TERRAFORM_VERSION}_linux_amd64.zip" | sha256sum -c - && \
    unzip -q terraform_${TERRAFORM_VERSION}_linux_amd64.zip -d /usr/local/bin && \
    rm terraform_${TERRAFORM_VERSION}_linux_amd64.zip

# Create necessary directories and set permissions
RUN mkdir -p /lemc/private /lemc/public /app/terraform-config

# Copy the built application from the builder stage
COPY --from=builder /app/main /usr/local/bin/main

# Copy terraform configuration files into the image
# The main.go program expects 'terraform-config' in its current working directory
COPY terraform-config /app/terraform-config/

# Set up the working directory
WORKDIR /app

# Set default command, can be overridden
CMD ["main"]
