#!/bin/sh
### BEGIN INIT INFO
# Provides:          dur-binfmt
# Required-Start:    $local_fs
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Register binfmt.d formats without systemd
### END INIT INFO
# qemu-user-binfmt only ships /usr/lib/binfmt.d for systemd-binfmt; without
# systemd (Devuan, the throwaway VM) nothing registers them, so foreign
# programs (tests in cross builds, piuparts of other architectures) would
# not run.  This does what systemd-binfmt does: /etc/binfmt.d overrides
# /usr/lib/binfmt.d by file name.  TODO: binfmt-support could read
# binfmt.d itself (upstream).
[ "${1:-start}" = start ] || exit 0
d=/proc/sys/fs/binfmt_misc
[ -e $d/register ] || mount -t binfmt_misc binfmt_misc $d || exit 0
for f in /etc/binfmt.d/*.conf /usr/lib/binfmt.d/*.conf; do
    [ -e "$f" ] || continue
    case $f in
        /usr/lib/*) [ ! -e "/etc/binfmt.d/${f##*/}" ] || continue ;;
    esac
    grep -v '^[#;]' "$f" | while read -r line; do
        [ -n "$line" ] || continue
        # :name:type:offset:magic:mask:interpreter:flags (any delimiter)
        sep=$(printf '%s' "$line" | cut -c1)
        name=$(printf '%s' "$line" | cut -d "$sep" -f2)
        interpreter=$(printf '%s' "$line" | cut -d "$sep" -f7)
        # emulators left out of the image (build-isolation-image.sh)
        [ -x "$interpreter" ] || continue
        [ -e "$d/$name" ] || printf '%s' "$line" > $d/register
    done
done
exit 0
