#!/usr/bin/env bash

set -eo pipefail

# gha-docker-build: build a Docker image with some caching help

# This script only works in CI.
if [[ -z "${GITHUB_ACTIONS}" ]]; then
  >&2 echo "Fatal: Only works in GitHub Actions."
  exit 1
fi

# This should already be set in the CI, but just in case.
export DOCKER_BUILDKIT=1

# Extremely annoying: the `pull_request` even creates a merge commit,
# which means that `GITHUB_SHA` is completely useless to key off of.
# We have to do some additional sleuthing for these events to get the right
# commit.
if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
  ref="${ACTUAL_GITHUB_SHA_ON_PULL_REQUEST}"
else
  ref="${GITHUB_SHA}"
fi

file="${1}.dockerfile"
name="${2}"

if [[ -z "${file}" || -z "${name}" ]]; then
  >&2 echo "Usage: gha-docker-build <dockerfile-name> <image-name>"
  exit 1
fi

full_image_name="ghcr.io/galoisinc/${name}"

# To speed the Docker build up, we use two image cache sources:
# * The current HEAD~1 (generally, the previous commit)
# * The most recent `:main`-tagged image
prev_ref=$(git rev-parse "${ref}~1" || true)

>&2 echo "Building ${full_image_name}:${ref} from ${file}"

# Do the actual build. We need to explicitly enable BuildKit's inline cache,
# for reasons that I don't know.
cd docker
docker build \
  --file "${file}" \
  --build-arg BUILDKIT_INLINE_CACHE=1 \
  --build-arg "UBUNTU_NAME=${UBUNTU_NAME:?Please set UBUNTU_NAME}" \
  --build-arg "CLANG_VERSION=${CLANG_VERSION:?Please set CLANG_VERSION}" \
  --build-arg "LLVM_MAJOR_VERSION=${LLVM_MAJOR_VERSION:?Please set LLVM_MAJOR_VERSION}" \
  --build-arg "UBUNTU_VERSION=${UBUNTU_VERSION:?Please set UBUNTU_VERSION}" \
  --cache-from "${full_image_name}:${prev_ref}" \
  --cache-from "${full_image_name}:main" \
  --tag "${full_image_name}:${ref}" \
  ..
cd ..

if [[ "${PUSH}" == "true" ]]; then
  docker push "${full_image_name}:${ref}"

  docker tag "${full_image_name}:${ref}" "${full_image_name}:main"
  docker push "${full_image_name}:main"

  docker tag "${full_image_name}:${ref}" "${full_image_name}:v$(./scripts/version.sh)"
  docker push "${full_image_name}:v$(./scripts/version.sh)"
fi

>&2 echo "[+] OK"
