#!/bin/sh

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

. /usr/share/initramfs-tools/hook-functions

# Many dri modules are kmsro, use a symlink there
dri_inst() {
    for so in "${libdir}"/dri/*_dri.so "${libdir}"/gbm/*_gbm.so; do
        if [ -L "${so}" ]; then
            mkdir -p "$(dirname "${DESTDIR}/${so}")"
            cp -P "${so}" "${DESTDIR}/${so}"
        else
            copy_exec "${so}"
        fi
    done
}

case "$DPKG_ARCH" in
    arm64)
        libdir=/usr/lib/aarch64-linux-gnu
        dri_inst
        copy_exec "$libdir/libGLESv2.so.2"

        # Pinephone
        if grep -q "allwinner" /proc/device-tree/compatible 2>/dev/null; then
            manual_add_modules goodix goodix_ts
        # Librem 5 and Librem 5 Devkit
        elif grep -q "imx" /proc/device-tree/compatible 2>/dev/null; then
            manual_add_modules edt-ft5x06 goodix pwm_vibra goodix_ts
        # PinePhone Pro
        elif grep -q "PinePhonePro" /proc/device-tree/model 2>/dev/null; then
            manual_add_modules goodix pwm_vibra goodix_ts
        # Generic / Installer (needs to include all of the above)
        else
            manual_add_modules edt-ft5x06 goodix pwm_vibra goodix_ts
        fi
        ;;
    amd64)
        libdir=/usr/lib/x86_64-linux-gnu
        dri_inst
        copy_exec "$libdir/libGLESv2.so.2"
        manual_add_modules hid_multitouch i2c_hid_acpi
        ;;
    *)
        echo "osk-sdl unsupported arch: $DPKG_ARCH"
        exit 0
        ;;
esac

find -L "$libdir" -name "libGL*.so*" -o -name "libEGL*.so*" -o -name "libEGL_mesa.so*" -type f | while read -r so; do
    copy_exec "$so"
done

if ! copy_exec /usr/bin/osk-sdl; then
    echo "ERROR: Couldn't copy /bin/osk-sdl" >&2
    exit 1
fi

if ! copy_file text /etc/osk.conf; then
    echo "ERROR: Couldn't copy config file for osk-sdl: /etc/osk.conf"
    exit 1
fi

if ! copy_exec /usr/share/initramfs-tools/scripts/osk-sdl-keyscript; then
    echo "ERROR: Couldn't copy osk-sdl keyscript" >&2
    exit 1
fi

copy_exec /sbin/dmsetup

# GLVND config needed for EGL
[ -f /usr/share/glvnd/egl_vendor.d/50_mesa.json ] && copy_file text /usr/share/glvnd/egl_vendor.d/50_mesa.json

ttf_font=$(sed  -ne  's/^keyboard-font\s*=\s*\(.*\)/\1/p' /etc/osk.conf)
if [ -n "${ttf_font}" ]; then
    copy_file font "$ttf_font"
else
    echo "ERROR: No font specified in /etc/osk.conf" >&2
    exit 1
fi

# crypto modules
manual_add_modules dm_mod
manual_add_modules dm_crypt
copy_modules_dir "kernel/crypto"
copy_modules_dir "kernel/arch/$DPKG_ARCH/crypto"

# Input Driver
manual_add_modules evdev
