#!/bin/bash
#
# PBA docker run wrapper
#
# (C) ITEG IT-Engineers GmbH 2010-2026
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# pba-docker-run
#
# This is intended to test-run the container the project (or directory) is supposed to build.
# If you want to use a docker image to perform build-time tasks in a temporary container use pba-dockerized-run 
#
# Runs the docker image specified by pba-docker-settings.txt
# If it's not present locally (!) it is rebuilt automatically by calling pba-docker-build
#
# For more advance demands write your own docker_run.sh or wait,
# we'll soon provide something based on ci-pba-docker-run

# params

. pba-docker-checksettings || exit $?
# exit values <20 come from there

OLDIMAGE_ID=$(docker images --format "{{.ID}}" ${IMAGE_NAME}:${IMAGE_TAG})
if [ -z "${OLDIMAGE_ID}" ] ; then
  echo "INFO: Found no image ${IMAGE_NAME}:${IMAGE_TAG}, calling pba-docker-build ..."
  pba-docker-build || exit 21
fi

test -f pba-docker-run.log && mv -v pba-docker-run.log pba-docker-run.log.bak

export IMAGE_TAG=$(echo "${IMAGE_TAGS}" |cut -f1 -d' ')
echo "INFO: Calling   docker run -it --name ${IMAGE_NAME} --rm $* ${IMAGE_NAME}:${IMAGE_TAG}" |tee pba-docker-run.log
docker run -it --name ${IMAGE_NAME} --rm $* ${IMAGE_NAME}:${IMAGE_TAG} 2>&1 |tee -a pba-docker-run.log
PRC=${PIPESTATUS[0]}
if [ "${PRC}" != "0" ] ; then
  echo "BAD: Running image ${IMAGE_NAME}:${IMAGE_TAG} gave us bad exit code '${PRC}', see pba-docker-run.log which starts with full docker run call"
  exit 22
fi

echo "GOOD: Successfully ran image ${IMAGE_NAME}:${IMAGE_TAG}, output was written to pba-docker-run.log"

exit 0


