#!/bin/bash

[ -n "$TMT_DEBUG" ] && set -x

TMT_TEST_PIDFILE="${TMT_TEST_PIDFILE:-/var/tmp/tmt-test.pid}"

if [ ! -e "$TMT_TEST_PIDFILE" ]; then
    echo "There is no running test to signal the reboot to!"
    exit 1
fi

command="$1"
timeout="$2"
systemd_soft_reboot="$3"

# Thanks to being run while holding the pidfile lock, the file exists and should
# no go away. It should be safe to read test PID and reboot-request filepath from
# it.
read -r test_pid test_reboot_file < "$TMT_TEST_PIDFILE"

mkdir -p "$(dirname "$test_reboot_file")"

# Build reboot-request JSON, including only non-empty command/timeout to satisfy
# strict Pydantic validation.
{
    printf '{'
    first=true
    [ -n "$command" ]             && { $first || printf ', '; printf '"command": "%s"' "$command";  first=false; }
    [ -n "$timeout" ]             && { $first || printf ', '; printf '"timeout": %s' "$timeout";    first=false; }
    [ -n "$systemd_soft_reboot" ] && { $first || printf ', '; printf '"systemd-soft-reboot": true'; first=false; }
    printf '}'
} > "$test_reboot_file"

# Flush buffers to prevent potential data loss
sync

kill "$test_pid"
