#!/bin/sh

# When running with debug in kernel command line, the "quiet" parameter is set
# to "y". So using standard logging functions will not work.
# Setting "quiet" to "y" does not help either since in that case initramfs log
# is written to /run/initramfs/initramfs.debug instead of /dev/kmsg.
# Use the following functions to see output in the console instead:

console_log() {
  echo "migrate-for-gce: initramfs: $*" > /dev/kmsg
}

run_and_console_log() {
  console_log "> $*"
  "$@" 2>&1 | while read -r line; do
    console_log "# $line"
  done
}

run_hook_and_log() {
  console_log "hook: $$: > $*"
  # Logging stderr too
  output=$("$@" 2>/tmp/err_$$)
  # Preserve return code
  rc=$?
  console_log "hook: $$: rc: $rc"
  err=$(cat /tmp/err_$$ 2>/dev/null)
  rm -f /tmp/err_$$
  if [ -n "${output}" ] ; then
    echo "${output}" | while read -r line; do
      console_log "$$: # $line"
    done
  fi
  if [ -n "${err}" ] ; then
    echo "${err}" | while read -r line; do
      console_log "$$: e $line"
    done
  fi
  # Return the output of the original process
  echo "${output}"
  >&2 echo "${err}"
  return $rc
}
