#!/bin/sh

set -e

PREREQ=""

prereqs()
{
    echo "$PREREQ"
}

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

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

COMMON_MODULES="evdev goodix goodix_ts"
# Needed for the Librem 5, PinePhone & PinePhone Pro
ARM64_MODULES="edt-ft5x06 goodix goodix_ts"
# Core modules needed for Qualcomm-based phones
QCOM_MODULES="gpi i2c_qcom_geni qcom_spmi_haptics"
# Touch controllers present in Qualcomm-based phones
QCOM_TS_MODULES="focaltech_fts novatek_nvt_ts rmi_i2c"

case "$DPKG_ARCH" in
    arm64)
        UNL0KR_MODULES="${ARM64_MODULES} ${QCOM_MODULES} ${QCOM_TS_MODULES} ${COMMON_MODULES}"
        ;;
    amd64)
        UNL0KR_MODULES="hid_multitouch i2c_hid_acpi ${COMMON_MODULES}"
        ;;
    *)
        echo "unl0kr unsupported arch: $DPKG_ARCH"
        exit 0
        ;;
esac

for mod in ${UNL0KR_MODULES}; do
    manual_add_modules $mod
done

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

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

if [ -f "/etc/unl0kr.conf" ]; then
    cp -pP /etc/unl0kr.conf ${DESTDIR}/etc/
fi

# Input Driver
cp -pPr /usr/share/libinput ${DESTDIR}/usr/share/
cp -pPr /etc/udev/rules.d ${DESTDIR}/etc/udev/
cp -pPr /usr/lib/udev/rules.d ${DESTDIR}/usr/lib/udev/

mkdir -p ${DESTDIR}/usr/share/X11/
cp -pPr /usr/share/X11/xkb ${DESTDIR}/usr/share/X11/

rm -f ${DESTDIR}/usr/lib/udev/rules.d/99-astra-input-labeling.rules

IS_KVADRAT="0"
IS_ZHISD="0"

if grep -q KVADRAT /etc/astra/machine_type ; then
    IS_KVADRAT="1"
fi

if grep -q 'ZHISD.arm64' /etc/astra/machine_type ; then
    IS_ZHISD="1"
fi

if [[ "${IS_KVADRAT}" == "1" || "${IS_ZHISD}" == "1" ]]; then
    rm -f ${DESTDIR}/usr/lib/udev/rules.d/60-persistent-storage.rules
fi
