#!/bin/bash
#
# PBA docker build 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.

# Call this to get a pba-utils configuration value echoed to stdout.
# The conf key has to be specified as $1.
# A conf value can be specified as $1.
# Eventual errors and warnings are echoed to stderr.
# 
# Conf values are searched in the following all-optional files with the last value winning.
# /etc/pba/utils.conf.template
# /etc/pba/utils.conf
# ~/.pba/utils.conf
# ./.pba/pba-utils.conf

# FIXME rename to bin withhout sh

if [ -z "$1" ] ; then
  ( echo "ERROR: No config key specified as \$1."
    echo ""
    echo "Syntax: pba-utils-config-get configKey [defaultValue]"
    echo ""
    echo "Configuration values are search for in following optional files, last key match wins."
    echo "/etc/pba/utils.conf.template /etc/pba/utils.conf ~/.pba/utils.conf ./.pba/pba-utils.conf"
    echo ""
  ) >&2
  exit 1
fi
export CONF_KEY="$1"
shift
#echo "DEBUG: CONF_KEY is: '${CONF_KEY}'" >&2

export CONF_VALUE_DEFAULT="$1"
shift
#echo "DEBUG: CONF_VALUE_DEFAULT is: '${CONF_VALUE_DEFAULT}'" >&2

if [ -n "$*" ] ; then
  echo "WARNING: More than 2 positional parameters specified, only searching for ${CONF_KEY}" >&2
fi

export CONF_FILES=""
if [ -f "/etc/pba/utils.conf.template" ] ; then
  CONF_FILES="${CONF_FILES} /etc/pba/utils.conf.template"
fi
if [ -f "/etc/pba/utils.conf" ] ; then
  CONF_FILES="${CONF_FILES} /etc/pba/utils.conf"
fi
if [ -f "~/.pba/utils.conf" ] ; then
  CONF_FILES="${CONF_FILES} ~/.pba/utils.conf"
fi
if [ -f "./.pba/pba-utils.conf" ] ; then
  CONF_FILES="${CONF_FILES} ./.pba/pba-utils.conf"
fi
if [ -z "${CONF_FILES}" ] ; then
  echo "ERROR: No config file found out of /etc/pba/utils.conf.template /etc/pba/utils.conf ~/.pba/utils.conf ./.pba/pba-utils.conf" >&2
  exit 11
fi
#echo "DEBUG: CONF_FILES are: ${CONF_FILES}" >&2

export CONF_VALUE=$(cat ${CONF_FILES} |egrep "^${CONF_KEY}:( |$)" |tail -1 |sed -e "s|^${CONF_KEY}: \?||g")
# we don't search for a space after ':' to allow setting explicitly empty without demanding a trailng space
#echo "DEBUG: CONF_VALUE is: '${CONF_VALUE}'" >&2

echo ${CONF_VALUE:-${CONF_VALUE_DEFAULT}}
# this should work with empty values specified as "" too

exit 0
