#!/bin/sh

set -e

# Create a dummy service file and emulate library change in the background
systemd-run -u dummy-background sleep infinity 2>/dev/null
ARCH=$(dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null)
LIBC=$(realpath /lib/$ARCH/libc.so.6)
cp "$LIBC" "${LIBC}.new"
mv -f "${LIBC}.new" "$LIBC"

OUTPUT=$(needrestart -b)

echo "Check if the mandatory version number is printed"
echo "$OUTPUT" | grep -q "^NEEDRESTART-VER:"

# Kernel checks are disabled when running in a container
if ! /usr/bin/systemd-detect-virt --container --quiet; then
    echo "Check if the correct kernel was detected"
    echo "$OUTPUT" | grep -q "^NEEDRESTART-KCUR: $(uname -r)$"

    echo "Check if the kernel status value is present as well"
    echo "$OUTPUT" | grep -q "^NEEDRESTART-KSTA: [0-3]$"
fi

echo "Check if outdated library was detected and dummy marked for restart"
echo "$OUTPUT" | grep -q "^NEEDRESTART-SVC: dummy-background.service$"
