#!/usr/bin/env bash
set -euo pipefail
source "../env"

# Arguments
THREADS="${1:-2}"

# Infos git
MANGOS_SHA1=$(curl -sSL "https://api.github.com/repos/cmangos/mangos-${WOW_VERSION}/commits/master" | jq -r .sha)
DATABASE_SHA1=$(curl -sSL "https://api.github.com/repos/cmangos/${WOW_VERSION}-db/commits/master" | jq -r .sha)

VERSION="1.0.0-$(date -u +"%Y%m%d")"
DOCKER_IMAGE="wow-server"

# Tags pour builder
BUILDER_IMAGE_TAG="${DOCKER_IMAGE}-${WOW_VERSION}:builder"
# Tags pour runner
RUNNER_IMAGE_TAG="${DOCKER_IMAGE}-${WOW_VERSION}:runner"

echo "==== Build de l’image BUILDER ===="
docker buildx build \
  --build-arg EXPANSION="${WOW_VERSION}" \
  --build-arg MANGOS_SHA1="${MANGOS_SHA1}" \
  --build-arg DATABASE_SHA1="${DATABASE_SHA1}" \
  --build-arg THREADS="${THREADS}" \
  --build-arg VERSION="${VERSION}" \
  --target builder \
  --tag "${BUILDER_IMAGE_TAG}" \
  --load \
  docker/

echo "==== Build de l’image RUNNER ===="
docker buildx build \
  --build-arg EXPANSION="${WOW_VERSION}" \
  --build-arg MANGOS_SHA1="${MANGOS_SHA1}" \
  --build-arg DATABASE_SHA1="${DATABASE_SHA1}" \
  --build-arg THREADS="${THREADS}" \
  --build-arg VERSION="${VERSION}" \
  --target runner \
  --tag "${RUNNER_IMAGE_TAG}" \
  --load \
  docker/

echo "==== Images construites ===="
docker images | grep "${DOCKER_IMAGE}"
