#!/bin/bash

# define variables.
IMAGE_VARIANT=fpm-alpine
IMAGE_VERSION=21
UPSTREAM_IMAGE=nextcloud
UPSTREAM_IMAGE_TAG=${IMAGE_VERSION}-${IMAGE_VARIANT}
IMAGE=bkraul/nextcloud

# set username and password
# requires vars DOCKER_USER and DOCKER_PASS to be defined before calling.

# useful functions.
function docker_tag_exists() {
    TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${DOCKER_USER}'", "password": "'${DOCKER_PASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)
    curl --silent -f --head -lL https://hub.docker.com/v2/repositories/$1/tags/$2/ > /dev/null
}

# pull the parent image from docker hub.
docker pull ${UPSTREAM_IMAGE}:${UPSTREAM_IMAGE_TAG}
UPSTREAM_ID=$(docker image inspect --format='{{index .Id}}' ${UPSTREAM_IMAGE}:${UPSTREAM_IMAGE_TAG})
UPSTREAM_ID=${UPSTREAM_ID:7}

# get the version number.
NEXTCLOUD_VERSION=$(docker inspect ${UPSTREAM_IMAGE}:${UPSTREAM_IMAGE_TAG} | jq -r '.[].Config.Env[] | select(match("^NEXTCLOUD_VERSION"))')
NEXTCLOUD_VERSION=${NEXTCLOUD_VERSION:18}
IMAGE_TAG=${NEXTCLOUD_VERSION}-${IMAGE_VARIANT}

if docker_tag_exists ${IMAGE} ${IMAGE_TAG}; then
    # nothing to do, the image already exists.
    echo Image ${IMAGE}:${IMAGE_TAG} already exists.
else
    exit 0
    # image doesn't exist we need build and push
    echo Image ${IMAGE}:${IMAGE_TAG} does not exist.
    echo "Building image(s)..."
    docker build $1 \
      -t ${IMAGE}:${UPSTREAM_IMAGE_TAG} \
      -t ${IMAGE}:${IMAGE_TAG}
    if [ $? == 0 ]; then
      echo "Pushing image(s)..."
      docker push ${IMAGE}:${IMAGE_TAG}
      docker push ${IMAGE}:${UPSTREAM_IMAGE_TAG}
    else
      echo "The build operation failed."
      echo "Please debug and try again."
    fi
fi