#!/bin/sh

set -ex

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

mount -t proc none /proc
mount -t sysfs none /sys
mount -t tmpfs none /mnt
mount -t tmpfs none /tmp

MAKE_TARGET="check"

# parse cmdline
for x in $(cat /proc/cmdline); do
  if [ "$x" = "shell" ]; then
    SHELL=1
  elif [ "$x" = "coverage" ]; then
    MAKE_TARGET="check-code-coverage"
  elif [ "$x" = "distcheck" ]; then
    MAKE_TARGET="distcheck"
  fi
done

hostname qemu-test

# loopback interface
ip addr add 127.0.0.1 dev lo
ip link set lo up

# main interface
ip link set eth0 up
ip addr add 10.0.2.15/24 dev eth0
ip link set eth0 up
ip route add default via 10.0.2.2
# /etc is not writable from here
echo "nameserver 10.0.2.3" > /tmp/resolv.conf
mount --bind /tmp/resolv.conf /etc/resolv.conf

# switch to rauc dir
cd "$(dirname "$0")"

# fake entropy
test/fakerand

# grub env
mkdir -p /tmp/boot/grub
mount --bind /tmp/boot /boot
grub-editenv test/grubenv.test create
touch /tmp/boot/grub/grubenv
mount --bind test/grubenv.test /tmp/boot/grub/grubenv

# dbus daemon
cp -a /etc/dbus-1/system.d /tmp
cp -a data/de.pengutronix.rauc.conf /tmp/system.d
chown root:root /tmp/system.d/de.pengutronix.rauc.conf
chmod 644 /tmp/system.d/de.pengutronix.rauc.conf
mount --bind /tmp/system.d /etc/dbus-1/system.d
mount -t tmpfs none /var/run
mkdir -p /var/run/dbus
time dbus-daemon --system --fork --nopidfile --nosyslog --print-address

if type losetup; then
  dd if=/dev/zero of=/tmp/rauc-disk.img bs=1M count=64
  losetup -P /dev/loop0 /tmp/rauc-disk.img
  export RAUC_TEST_BLOCK_LOOP=/dev/loop0
fi

if [ -c /dev/mtd2 ] && type flash_erase; then
  export RAUC_TEST_MTD_NAND=/dev/mtd2
fi

if [ -c /dev/mtd3 ] && type ubiattach; then
  ubiattach -m 3 -d 0
  ubimkvol /dev/ubi0 -s 12096KiB -N rauc-test
  export RAUC_TEST_MTD_UBI=/dev/ubi0
  export RAUC_TEST_MTD_UBIVOL=/dev/ubi0_0
fi

echo "system ready"

if [ -n "$SHELL" ]; then
  HISTFILE="$(pwd)/.qemu_bash_history" \
  setsid bash </dev/ttyS0 >/dev/ttyS0 2>&1 || echo exit-code=$?
  echo o > /proc/sysrq-trigger
fi

if make $MAKE_TARGET; then
  touch qemu-test-ok
else
  cat test-suite.log || true
  # show system status on error
  mount || true
  df -h || true
  free || true
fi
echo o > /proc/sysrq-trigger
sleep 1
