#!/bin/sh
# vim: ft=sh:
#
# This file is *not* executable as it is sourced by
# the rc.boot and rc.shutdown scripts

# shellcheck disable=1090,1091

log() {
  printf '\033[31;1m=>\033[m %s\n' "$@"

  # Only print to /dev/kmsg and /dev/null if they both exist.
  # This will fail late in the shutdown process and possibly
  # early on in the boot-up process.
  [ -w /dev/null ] && [ -w /dev/kmsg ] \
    &&
    # Additionally send all messages to /dev/kmsg so that they
    # appear in 'dmesg' and can be read post-boot.
    printf 'init: %s\n' "$@" 2>/dev/null >/dev/kmsg
}

mounted() {
  # This is a pure shell mountpoint implementation. We're dealing
  # with basic (and fixed/known) input so this doesn't need to
  # handle more complex cases.
  [ -e "$1" ] || return 1
  [ -e /proc/mounts ] || return 1

  while read -r _ target _; do
    [ "${target}" = "$1" ] && return 0
  done </proc/mounts

  return 1
}

mnt() {
  # If the filesystem is already mounted, mount it again with
  # 'remount' so that it uses the correct mount options. This is
  # usually the case when dealing with an initramfs for example.
  mounted "$4" && set -- "remount,$1" "$2" "$3" "$4"

  mount -o "$1" -t "$2" "$3" "$4"
}

sos() {
  log "Init system encountered an error, starting emergency shell." \
    "When ready, type 'exit' to continue the boot."

  /bin/sh
}

load_conf() {
  [ -f /etc/rc.conf ] && . /etc/rc.conf

  : "${CONFIG_INIT:=busybox}"
  : "${CONFIG_SERVICE:=runit}"
  : "${CONFIG_SERVICE_DIR:=/var/service}"
  : "${CONFIG_DEV:=mdev}"
}

run_hook() {
  for file in /usr/lib/init/rc.d/*."$1" /etc/rc.d/*."$1"; do
    [ -f "${file}" ] || continue

    log "Running $1 hook: ${file}"
    . "${file}"
  done
}

run_exec() {
  case ${CONFIG_INIT} in
    busybox | shinit)
      # These inits expect the script to eventually exit so we cannot use
      # exec without breaking poweroff/reboot or the boot process itself.
      setsid "$@" &
      ;;

    *)
      exec "$@"
      ;;
  esac
}

random_seed() {
  # https://freenode.logbot.info/kisslinux/20200108/raw
  seed=/var/lib/init/random-seed

  # shellcheck disable=SC2249
  case $1 in
    save)
      mkdir -p "${seed%/*}" || {
        log "Warning: Failed to create random seed directory."
        return 1
      }

      dd count=1 bs=512 if=/dev/urandom of="${seed}" \
        || log "Warning: Failed to seed random"
      ;;

    load)
      [ -f "${seed}" ] && cat "${seed}" >/dev/urandom
      ;;
  esac
}
