#!/bin/bash

set -e

# Build dokuwiki images.
# Set environ BUILD_PUSH to push build images.
# Set environ BUILD_EXTRA to add arguents to docker build command line.

# Define build image name. Define env BUILD_NAME to override.
declare BUILD_NAME=${BUILD_NAME:-docker.seblu.net/docker/dokuwiki}

# Dokuwiki upstream consider the last reliable version to be rc when available.
# The update_check in dokuwiki is always looking for RC too.
# https://forum.dokuwiki.org/d/8939-update-check-should-not-be-used-for-release-candidates
# so we tag latest rc when available, either stable or oldstable.
declare latest=''

# Declare well known versions. Order matter! Latest is the latest tag.
declare -r -A versions=(
  ["dev"]="http://github.com/splitbrain/dokuwiki/tarball/master"
  ["oldstable"]="https://download.dokuwiki.org/src/dokuwiki/dokuwiki-oldstable.tgz"
  ["stable"]="https://download.dokuwiki.org/src/dokuwiki/dokuwiki-stable.tgz"
  ["rc"]="https://download.dokuwiki.org/src/dokuwiki/dokuwiki-rc.tgz"
)

for version in "${!versions[@]}"; do
  # Do not build unavailable url (e.g: rc is only avaible before a new release)
  echo "Checking $version at ${versions[$version]}"
  curl -Isf "${versions[$version]}" -o /dev/null || continue
  echo "Building $version"
  docker build --build-arg=DOKUWIKI_URL="${versions[$version]}" --tag "$BUILD_NAME:$version" $BUILD_EXTRA .
  if [[ "$BUILD_PUSH" ]]; then
    echo Pushing "$BUILD_NAME:$version"
    docker push "$BUILD_NAME:$version"
  fi
  latest=$version
done

# The latest tag is special
if [[ "$latest" ]]; then
  echo "Tag latest is $latest"
  docker tag "$BUILD_NAME:$latest" "$BUILD_NAME:latest"
  if [[ "$BUILD_PUSH" ]]; then
    echo Pushing "$BUILD_NAME:latest"
    docker push "$BUILD_NAME:latest"
  fi
fi
