#!/bin/bash
#%stage: block
#
#%modules: dm-mod virtio_blk virtio_console virtio_net virtio_pci virtio_scsi sg sd_mod sr_mod 
#
#%programs: mdadm
#%programs: modprobe
#%programs: lvm
#%programs: grep
#%programs: ls
#%programs: cat
#%programs: ip
#%programs: date
#%programs: valgrind
#%programs: guestfsd
#
# Generated at build time:
#@GUESTFS_EXT_CMDS@
#
missing_commands="@GUESTFS_MISSING_CMDS@"

# Make the modules available now
# run_all.sh will load them after this script is sourced
load_modules

# from libguestfs-1.19.34/appliance/init:

# Scan for MDs.
mdadm -As --auto=yes --run

# Scan for LVM.
lvm vgscan --ignorelockingfailure
lvm vgchange -ay --ignorelockingfailure

# Improve virtio-blk performance (RHBZ#509383).
for f in /sys/block/vd*/queue/rotational; do if test -f $f ; then echo 1 > $f; fi ; done

# These are useful when debugging.
if grep -sq guestfs_verbose=1 /proc/cmdline; then
    ls -lR /dev
    cat /proc/mounts
    lvm pvs
    lvm vgs
    lvm lvs
    ip a
    ip r
    cat /proc/modules
    #hwclock -r
    date
    #ping -n -v -c 5 10.0.2.2
    #ping -n -v -c 5 10.0.2.4

    echo -n "uptime: "; cat /proc/uptime
fi

echo "These commands might be called by guestfsd, but they were not available at buildtime:"
echo "missing commands: $missing_commands"
echo
if ! grep -sq guestfs_rescue=1 /proc/cmdline; then
  # Run the daemon under valgrind if ./configure --enable-valgrind-daemon
  vg_channel=/dev/virtio-ports/org.libguestfs.valgrind
  if [ -w $vg_channel ]; then
    if [ -r /etc/guestfsd.suppressions ]; then
      suppressions="--suppressions=/etc/guestfsd.suppressions"
    fi
    exec 3>$vg_channel
    vg="valgrind --leak-check=full --log-fd=3 --error-exitcode=119 --max-stackframe=8388608 --child-silent-after-fork=yes $suppressions"
    echo "enabling valgrind: $vg"
  fi

  # The host will kill qemu abruptly if guestfsd shuts down normally
  $vg guestfsd

  # Otherwise we try to clean up gracefully. For example, this ensures that a
  # core dump generated by the guest daemon will be written to disk.
else
  # Use appliance in rescue mode, also used by the virt-rescue command.
  eval $(grep -Eo 'TERM=[^[:space:]]+' /proc/cmdline)
  PS1='><rescue> '
  export TERM PS1
  echo
  echo "------------------------------------------------------------"
  echo
  echo "Welcome to virt-rescue, the libguestfs rescue shell."
  echo
  echo "Note: The contents of / are the rescue appliance."
  echo "You have to mount the guest's partitions under /sysroot"
  echo "before you can examine them."
  echo
  bash -i
  echo
  echo "virt-rescue: Syncing the disk now before exiting ..."
  echo
fi

echo "Leaving."
echo s > /proc/sysrq-trigger
echo b > /proc/sysrq-trigger
exit 0