#!/bin/sh
#
# Answer host DEK requests over the DDR mailbox (B0, 2026-10-28).
#
# Nothing is published at boot: the daemon waits for a QDEK request, unseals the
# DEK into a random page inside the PCIe window, and wipes it on the host's ack
# or after the window expires. No request => no plaintext in DDR.
#
# Runs after S99xdma (link name is S99zdekrelease) and waits for the PL to be
# configured, so a request can only be served once the host can read DDR.
#
case "$1" in
  start)
    if [ ! -x /home/root/dek-release ]; then
      echo "dekrelease: /home/root/dek-release missing" > /dev/kmsg 2>/dev/null
      exit 1
    fi

    i=0
    while [ $i -lt 30 ]; do
      state=$(cat /sys/class/fpga_manager/fpga0/state 2>/dev/null)
      [ "$state" = "operating" ] && break
      i=$((i + 1))
      sleep 1
    done
    echo "dekrelease: fpga state=$state, starting request server at uptime $(cut -d' ' -f1 /proc/uptime)s" > /dev/kmsg 2>/dev/null

    /sbin/start-stop-daemon -S -b -m -p /var/run/dek-release.pid \
      -x /home/root/dek-release -- -mode serve -window 30s -poll 100ms
    ;;
  stop)
    /sbin/start-stop-daemon -K -p /var/run/dek-release.pid -x /home/root/dek-release
    ;;
  *)
    echo "usage: $0 {start|stop}"
    exit 1
    ;;
esac
