#!/bin/sh
### BEGIN INIT INFO
# Provides:          vdev-modprobe
# Required-Start:
# Required-Stop:
# Should-Start:      glibc
# Default-Start:     S
# Default-Stop:
# Short-Description: Load drivers
### END INIT INFO

# Top priority: find out the JSON file
# If there is no environment variable, we search the system's default path
_json="${VDEV_GLOBALS_JSON:-/etc/vdev/vdevd.globals.json}"

if [ -r "$_json" ] && command -v jq >/dev/null 2>&1; then
    # Clean up comments // and also /* */
	VDEV_JSON_DATA="$(sed -E 's|//.*||g' "$_json" |
        sed 's|/\*.*\*/||g' |
        grep -v '^$' |
        jq -r .)"
    export VDEV_JSON_DATA
else
    # Fallback if there is no JSON
    VDEV_CONFIG_DIR="/etc/vdev"
    VDEV_MODPROBE="vdevd.0.conf"
    VDEV_MODPROBE_STAMP="/run/vdev/vdevd-0-coldplug.ready"
fi

get_json_get_key() {
    printf '%s' "$VDEV_JSON_DATA" | jq -r --arg k "$1" '
      .globals[$k] // empty
    ' 2>/dev/null
}

get_json_get_config() {
    printf '%s' "$VDEV_JSON_DATA" | jq -r --arg s "$1" '
      .states[$s].config // empty
    ' 2>/dev/null
}

get_json_get_stamp() {
    printf '%s' "$VDEV_JSON_DATA" | jq -r --arg s "$1" '
      .states[$s].stamp // empty
    ' 2>/dev/null
}

if [ -n "$VDEV_JSON_DATA" ]; then
    
    _config_dir="$(get_json_get_key "config-dir")"
    VDEV_CONFIG_DIR="${_config_dir:-/etc/vdev}"

    _modprobe="$(get_json_get_config "modprobe")"
    VDEV_MODPROBE="${_modprobe:-vdevd.0.conf}"
    
    _stamp_dir="$(get_json_get_key "states-stamp-dir")"
    VDEV_STAMP_DIR="${_stamp_dir:-/run/vdev}"

    _stamp_modprobe="$(get_json_get_stamp "modprobe")"
    VDEV_MODPROBE_STAMP="${VDEV_STAMP_DIR}/${_stamp_modprobe:-vdevd-0-coldplug.ready}"

    _json_modprobe_bg="$(printf '%s' "$VDEV_JSON_DATA" |
        jq -r '(.globals["modprobe-phase-background"] // false)' 2>/dev/null)"
fi

# Fallbacks
VDEV_BIN="${VDEV_BIN:-/sbin/vdevd}"
[ -x "$VDEV_BIN" ] || exit 0

VDEV_MOUNTPOINT="${VDEV_MOUNTPOINT:-/dev}"

# Prefer VDEV_MODPROBE_BACKGROUND from the environment; else globals["modprobe-phase-background"] (default false).
case "${VDEV_MODPROBE_BACKGROUND:+x}" in
    x) ;;
    *) VDEV_MODPROBE_BACKGROUND="${_json_modprobe_bg:-false}" ;;
esac

case "$1" in
    start)
        # Cleanup the stamp
        rm -f "$VDEV_MODPROBE_STAMP" 2>/dev/null || true

        # Primary PCI boot VGA: load KMS early so DRM nodes exist before vdevd coldplug
        for boot_file in /sys/bus/pci/devices/*/boot_vga; do
            if [ -f "$boot_file" ] && [ "$(cat "$boot_file")" = "1" ]; then
                pci_dir=$(dirname "$boot_file")
                if [ -f "$pci_dir/modalias" ]; then
                    alias_string=$(cat "$pci_dir/modalias")
                    case "$alias_string" in
                    # named modules: i915|nouveau|amdgpu
                    *v00008086*|*v000010DE*|*v00001002*)
                        modprobe -q "$alias_string" 2>/dev/null || true
                        ;;
                    *)
                        [ -n "$alias_string" ] && modprobe -q "nouveau" 2>/dev/null || true
                        ;;
                    esac
                    break
                fi
            fi
        done
        export VDEV_JSON_STATE=modprobe
        modprobe -q fuse 2>/dev/null || true
        modprobe -q usbcore
        modprobe -q xhci_hcd
        "$VDEV_BIN" -c "${VDEV_CONFIG_DIR}/${VDEV_MODPROBE}" "$VDEV_MOUNTPOINT"
        ;;
    stop|restart|force-reload|status)
        # No-op
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|status}" >&2
        exit 1
        ;;
esac
