#!/usr/bin/env bash
set -euo pipefail

IMAGE="registry.bstein.dev/bstein/ananke-node-helper:0.1.0"
DOCKER_CONFIG_PATH=""
PLATFORMS="linux/amd64,linux/arm64"
BUILDER_NAME="ananke-node-helper-builder"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --image)
      IMAGE="${2:?missing image}"
      shift 2
      ;;
    --docker-config)
      DOCKER_CONFIG_PATH="${2:?missing docker config path}"
      shift 2
      ;;
    --platforms)
      PLATFORMS="${2:?missing platforms}"
      shift 2
      ;;
    --builder)
      BUILDER_NAME="${2:?missing builder}"
      shift 2
      ;;
    -h|--help)
      cat <<USAGE
Usage: scripts/ops/build_ananke_node_helper.sh [--image <image>] [--docker-config <path>] [--platforms <csv>] [--builder <name>]
USAGE
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      exit 1
      ;;
  esac
done

if [[ -n "${DOCKER_CONFIG_PATH}" ]]; then
  export DOCKER_CONFIG="${DOCKER_CONFIG_PATH}"
fi

if ! docker buildx inspect "${BUILDER_NAME}" >/dev/null 2>&1; then
  docker buildx create --name "${BUILDER_NAME}" --driver docker-container --use >/dev/null
else
  docker buildx use "${BUILDER_NAME}" >/dev/null
fi

docker buildx inspect --bootstrap >/dev/null
docker buildx build \
  --platform "${PLATFORMS}" \
  -f dockerfiles/Dockerfile.ananke-node-helper \
  -t "${IMAGE}" \
  --push \
  .
