#!/bin/bash
# This post build hook creates multi-architecture docker manifests.
# It's all a bit complicated for some reason.
# This is part of Application Builder.
# https://github.com/golift/application-builder

pushd ../..
source settings.sh
popd

if [ "$BUILDS" != "" ]; then
  TAGS=$DOCKER_TAG
fi

export DOCKER_CLI_EXPERIMENTAL=enabled

# Push the extra custom images that were created.
for build in $BUILDS; do
  os=$(echo $build | cut -d: -f1)
  name=$(echo $build | cut -d: -f2)
  echo "Pushing Image ${IMAGE_NAME}_${os}_${name}"
  docker push ${IMAGE_NAME}_${os}_${name}
  IMAGES="${IMAGES} ${IMAGE_NAME}_${os}_${name}"
done
echo "Annotating Images: ${IMAGES}"

# Build all the Docker tags if the source branch is a release and not a branch or pre-release.
if [ "v$VERSION" = "$SOURCE_BRANCH" ]; then
  TAGS="$VERSION"

  echo $SOURCE_BRANCH | grep -q -- -
  if [ "$?" = "1" ]; then
    # tag does not contain a dash, so assume it's a prod tag.
    TAGS="$TAGS latest stable $(echo $VERSION | cut -d. -f1,2) $(echo $VERSION | cut -d. -f1)"
  fi
fi

echo "Version: $VERSION, Source: $SOURCE_BRANCH, Building tags: ${TAGS}"

# Create multi-architecture manifests for each tag with all the built images.
for tag in $TAGS; do
  docker manifest create --amend ${DOCKER_REPO}:${tag} $IMAGES
  for build in $BUILDS; do
    # os:name:arch, ie linux:amd64:amd64
    os=$(echo $build | cut -d: -f1)
    name=$(echo $build | cut -d: -f2)
    arch=$(echo $build | cut -d: -f3)
    # Annotating updates the manifest to describe each images' capabilities.
    docker manifest annotate ${DOCKER_REPO}:${tag} ${IMAGE_NAME}_${os}_${name} --os ${os} --arch ${arch}
  done
  echo "Pushing Manifest ${DOCKER_REPO}:${tag}"
  docker manifest push ${DOCKER_REPO}:${tag}
done
