#!/bin/sh
#        file: /usr/bin/bootcd
#   copyright: Bernd Schumacher <bernd.schumacher@hpe.com> (2001-2019)
#     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")"
      [ -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

  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

  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
  done

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

LANG=C
LC_ALL=C

read_libraries
eval "$ia_init"
ia_add "read_opts $(split_args "$@"); err=\$?"
ia_nocheck && ia_add "if [ $<err> -ge 100 ]; then exit \$((err -100)); fi"
ia_nocheck && ia_add "$(basename $0) <-i>"
ia -c
