#!/bin/bash

KVADRAT_USB_DEVICES_PATH="/tmp/kvadra-t"
KVADRAT_PLUGGABLE_KEYBOARD_PATH="$KVADRAT_USB_DEVICES_PATH/pluggable-keyboard"

echo "ACTION==\"add\", SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"1c4f\", ATTRS{idProduct}==\"0063\", RUN+=\"/bin/bash -c 'mkdir -p $KVADRAT_USB_DEVICES_PATH; ln -sf /sys/\$devpath $KVADRAT_PLUGGABLE_KEYBOARD_PATH; echo auto > $KVADRAT_PLUGGABLE_KEYBOARD_PATH/power/control; echo 7000 > $KVADRAT_PLUGGABLE_KEYBOARD_PATH/power/autosuspend_delay_ms'\"" > /etc/udev/rules.d/99-ts11-enable-suspend-for-keyboard.rules

cat > /usr/lib/systemd/system-sleep/ts11-disable-keyboard <<EOF
#!/bin/bash

case "\$1" in
    pre)
        if [ -f $KVADRAT_PLUGGABLE_KEYBOARD_PATH/idVendor ]; then
            if grep "1c4f" $KVADRAT_PLUGGABLE_KEYBOARD_PATH/idVendor; then
                echo vbus1-5v0-typec > /sys/bus/platform/drivers/reg-fixed-voltage/unbind
                touch /tmp/unbind_regulator
            fi
        fi
        ;;
    post)
        if [ -f /tmp/unbind_regulator ]; then
           echo vbus1-5v0-typec > /sys/bus/platform/drivers/reg-fixed-voltage/bind
           rm /tmp/unbind_regulator
        fi
        ;;
esac
EOF

chmod +x /usr/lib/systemd/system-sleep/ts11-disable-keyboard

cat > /usr/lib/systemd/system-shutdown/ts11-disable-keyboard <<EOF
#!/bin/bash

if [ -f $KVADRAT_PLUGGABLE_KEYBOARD_PATH/idVendor ]; then
    if grep "1c4f" $KVADRAT_PLUGGABLE_KEYBOARD_PATH/idVendor; then
        echo vbus1-5v0-typec > /sys/bus/platform/drivers/reg-fixed-voltage/unbind
    fi
fi
EOF

chmod +x /usr/lib/systemd/system-shutdown/ts11-disable-keyboard

