#!/bin/bash

# sourcing our current rc.conf requires this to be a bash script
. /usr/lib/rc/functions

mount_binfmt(){
    mountpoint -q /proc/sys/fs/binfmt_misc || \
    mount -t binfmt_misc binfmt /proc/sys/fs/binfmt_misc || return 1

    for files in /proc/sys/fs/binfmt_misc/*; do
        [ "$files" = /proc/sys/fs/binfmt_misc/register ] && continue
        [ "$files" = /proc/sys/fs/binfmt_misc/status ]   && continue
        echo -1 > "$files"
    done

    for path in /usr/lib/binfmt.d /etc/binfmt.d /run/binfmt.d; do
        [[ ! -d $path ]] && continue
        [[ -z "$(ls $path)" ]] && continue
        grep -h "^:" $path/* | \
            while read -r line; do
                printf "%s" "$line" > /proc/sys/fs/binfmt_misc/register || return 1
            done
    done
    return 0
}



case "$1" in
    start)
        stat_busy "Running binfmt"
        mount_binfmt || stat_die binfmt
        add_daemon binfmt
        stat_done binfmt
        ;;
    once)
        stat_busy "Running binfmt"
        mount_binfmt || stat_die binfmt
        stat_done
        ;;
    *)
        echo "usage: $0 {start|once}"
        exit 1
        ;;
esac
