#!/bin/sh
# Select Xorg display mode based on kernel cmdline.
# Default is the current server-safe path: keep forced fbdev.
set -eu

cmdline_param() {
    key="$1"
    for token in $(cat /proc/cmdline 2>/dev/null); do
        case "$token" in
            "$key"=*)
                echo "${token#*=}"
                return 0
                ;;
        esac
    done
    return 1
}

log() {
    echo "bee-display-mode: $*"
}

mode="$(cmdline_param bee.display || true)"
if [ -z "$mode" ]; then
    mode="safe"
fi

xorg_dir="/etc/X11/xorg.conf.d"
fbdev_conf="${xorg_dir}/10-fbdev.conf"
fbdev_park="${xorg_dir}/10-fbdev.conf.disabled"

mkdir -p "$xorg_dir"

case "$mode" in
    kms|auto)
        if [ -f "$fbdev_conf" ]; then
            mv "$fbdev_conf" "$fbdev_park"
            log "mode=${mode}; disabled forced fbdev config"
        else
            log "mode=${mode}; fbdev config already disabled"
        fi
        ;;
    safe|fbdev|"")
        if [ -f "$fbdev_park" ] && [ ! -f "$fbdev_conf" ]; then
            mv "$fbdev_park" "$fbdev_conf"
            log "mode=${mode}; restored forced fbdev config"
        else
            log "mode=${mode}; keeping forced fbdev config"
        fi
        ;;
    *)
        log "unknown bee.display=${mode}; keeping forced fbdev config"
        ;;
esac
