#!/bin/bash

set -e  # Abort on error

DOCKER_IMAGE_PREFIX=${DOCKER_IMAGE_PREFIX:-my_ocrd_workflow}  # default to locally built
DOCKER_IMAGE_TAG=${DOCKER_IMAGE_TAG:-latest}
LOG_LEVEL=${LOG_LEVEL:-INFO}

self=`realpath $0`
self_dir=`dirname "$self"`


# Docker run options
docker_run_options="--rm -t"
docker_run_options="$docker_run_options --mount type=bind,src=\"$(pwd)\",target=/data"
# In podman, the container always runs as the real user == uid 0 in container
if docker -v 2>&1 | grep -q podman; then
  user="0:0"
else
  user="`id -u`:`id -g`"
fi
docker_run_options="$docker_run_options --user $user"
docker_run_options="$docker_run_options -e LOG_LEVEL=$LOG_LEVEL"
# The containers currently need to run privileged to allow it to read from e.g.
# /home on SELinux secured systems such as Fedora. We might want to use udica
# instead in the future.
docker_run_options="$docker_run_options --privileged=true"


# Build aliases for the containerized ocrd processors
build_alias() {
  local command=$1
  local docker_image=$2

  alias $command="docker run $docker_run_options $docker_image $command"
}
shopt -s expand_aliases  # Required for non-interactive shells
build_alias ocrd                       ${DOCKER_IMAGE_PREFIX}-core:${DOCKER_IMAGE_TAG}
build_alias ocrd-olena-binarize        ${DOCKER_IMAGE_PREFIX}-ocrd_olena:${DOCKER_IMAGE_TAG}
build_alias ocrd-sbb-binarize          ${DOCKER_IMAGE_PREFIX}-sbb_binarization:${DOCKER_IMAGE_TAG}
build_alias ocrd-sbb-textline-detector ${DOCKER_IMAGE_PREFIX}-sbb_textline_detector:${DOCKER_IMAGE_TAG}
build_alias ocrd-calamari-recognize    ${DOCKER_IMAGE_PREFIX}-ocrd_calamari:${DOCKER_IMAGE_TAG}
build_alias ocrd-tesserocr-recognize   ${DOCKER_IMAGE_PREFIX}-ocrd_tesserocr:${DOCKER_IMAGE_TAG}
build_alias ocrd-dinglehopper          ${DOCKER_IMAGE_PREFIX}-dinglehopper:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-clip       ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-resegment  ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-segment    ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-deskew     ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-denoise    ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-binarize   ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-dewarp     ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}
build_alias ocrd-cis-ocropy-recognize  ${DOCKER_IMAGE_PREFIX}-ocrd_cis:${DOCKER_IMAGE_TAG}


. $self_dir/my_ocrd_workflow