#!/bin/sh
#        file: /usr/bin/bootcd
#   copyright: Bernd Schumacher <bernd.schumacher@hpe.com> (2001-2020)
#     license: GNU General Public License, version 3
# description: bootcd - load bootcd libs and start called script

# do not use "set -e", because even a grep will fail, if all output is filtered
set -u

# err - will be overwritten from read_libraries
err()
{
  echo "ERROR: $1" >&2
  exit 1
}

# find_bootcd_file <lib>
# example:
#   programm "/nfs/host1/usr/local/bin/program" with line "ia_source_lib /usr/share/shellia/ia" called
#   from directory "/tmp" will try "/tmp/ia", ... "/nfs/host1/usr/share/shellia/ia", ... and
#   "/usr/share/shellia/ia" in the listed order.
find_bootcd_file()
{
  local i
  local p

  for i in "$@"; do
    [ -f "./$(basename "$i")" ] && echo "./$(basename "$i")" && return 0
    p="$0"
    while :; do
      [ "$p" != "$(dirname p)" ] || break
      p="$(dirname "$p")"
      [ "$p" = "/" -a -f "$i" ] && echo "$i" && return 0
      [ -f "$p$i" ] && echo "$p$i" && return 0
      [ "$p" != "/" ] || break
    done
    [ -f "$i" ] && echo "$i" && return 0
    return 1
  done
}

read_libraries()
{
  local old_ia_logfile
  local i
  local f
  local b
  local libs

  old_ia_logfile="${ia_logfile:=}"

  if ! [ "$ia_logfile" ]; then
    if touch "/var/log/$(basename $0)" 2>/dev/null; then
      ia_logfile="/var/log/$(basename $0)"
    elif touch "/var/log/$(basename $0)" 2>/dev/null; then
      ia_logfile="/var/log/$(basename $0)"
    else
      ia_logfile="/dev/null"
      echo "WARNING: logfile is not writeable, logging disabled" >&2
    fi
    [ -f $ia_logfile.2 ] && mv $ia_logfile.2 $ia_logfile.3
    [ -f $ia_logfile.1 ] && mv $ia_logfile.1 $ia_logfile.2
    [ -f $ia_logfile ] && mv $ia_logfile $ia_logfile.1
  fi

  libs=""
  b=/usr/share/bootcd
  for i in /usr/share/shellia/ia $b/bootcd-run.lib $b/bootcd-check.lib \
    $b/bootcd.lib $b/bootcd-usage.lib $b/bootcd2disk-check.lib \
    $b/bootcd2disk.lib $b/bootcdwrite.lib $b/bootcdmk2diskconf.lib \
    $b/bootcdbackup.lib $b/bootcdconf.lib
  do
    f="$(find_bootcd_file $i)" || err "no file $i"
    . $f
    [ "$libs" ] && libs="$libs $f" || libs="$f"
  done

  if [ "$ia_logfile" != "/dev/null" ]; then
    [ "$old_ia_logfile" ] || dbg "To see full output: tail -f $ia_logfile"
    date "+%Y/%m/%d %H:%M" | log
  fi
  export ia_logfile
  LIBRARIES="$libs"
}

LANG=C
LC_ALL=C

read_libraries
eval "$ia_init"
ia_add "dbglog \"LIBRARIES=<$LIBRARIES>\""
ia_add "read_opts $(split_args "$@"); err=\$?"
ia_nocheck && ia_add "[ $<err> -eq 0 ] || exit $<err>"
if  [ "$(type "lib_dev_test" 2>/dev/null | head -1 | grep "function")" ]; then
  ia_nocheck && ia_add "lib_dev_test"
else
  ia_nocheck && ia_add "$(basename $0) <-i>"
fi
ia -c
