# 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.
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
ARG GCLOUD_VERSION=578.0.0
ARG GCLOUD_GENERATION=1785245315707220
ARG GCLOUD_SHA256=322ac42ef7670cf2e16d46a1c3f827b36e55a865d2e26f34c64c914869e400f0
RUN apk add --no-cache wget unzip ca-certificates git openssh-client make python3 py3-pip bash

# Install Google Cloud CLI from an exact Google Cloud Storage generation.
RUN wget -q -O google-cloud-cli.tar.gz "https://storage.googleapis.com/download/storage/v1/b/cloud-sdk-release/o/google-cloud-cli-${GCLOUD_VERSION}-linux-x86_64.tar.gz?generation=${GCLOUD_GENERATION}&alt=media" && \
    echo "${GCLOUD_SHA256}  google-cloud-cli.tar.gz" | sha256sum -c - && \
    tar -xzf google-cloud-cli.tar.gz -C /opt && \
    test "$(cat /opt/google-cloud-sdk/VERSION)" = "${GCLOUD_VERSION}" && \
    rm google-cloud-cli.tar.gz

# Add gcloud to PATH
ENV PATH="/opt/google-cloud-sdk/bin:${PATH}"

# 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/
COPY files /app/files/

# Set up the working directory
WORKDIR /app

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