#!/bin/sh
# SPDX-License-Identifier: GPL-2.0+
# Copyright 2021-2023 Lukas F. Hartmann <lukas@mntre.com>
# Copyright 2022-2025 Johannes Schauer Marin Rodrigues <josch@mister-muffin.de>
#
# MNT Reform Standby Handler (For i.MX8MQ)
# Thanks to ruff for contributions

set -eu

usage() {
  echo "i.MX8MQ specific setup before suspend and after wakeup." >&2
  echo "This script is called by the reform-sleep.service systemd service." >&2
  echo "Do not call this script manually from the terminal but use" >&2
  echo "systemctl suspend instead." >&2
  echo >&2
  echo "Usage: $0 [--help] suspend|resume" >&2
  echo >&2
  echo "Options:" >&2
  echo "  --help           Display this help and exit." >&2
}

if [ "$#" -gt 0 ] && [ "$1" = "--help" ]; then
  usage
  exit 0
fi

if [ "$(id -u)" -ne 0 ]; then
  echo "reform-standby has to be run as root / using sudo."
  exit
fi

case "$(cat /proc/device-tree/model)" in
  "MNT Reform 2" | "MNT Reform 2 HDMI") : ;;
  *)
    echo "Sorry, reform-standby is only supported on MNT Reform 2 with i.MX8MQ processor module."
    exit
    ;;
esac

wifi_off() {
  echo 1 >/sys/class/pci_bus/0000:01/device/remove
}

wifi_on() {
  echo 1 >/sys/class/pci_bus/0000:00/rescan
  sleep 1
}

hantro_off() {
  # with 5.18, hantro_vpu hangs on resume
  rmmod hantro_vpu
}

hantro_on() {
  modprobe hantro_vpu
}

kbd_backlight_off() {
  for d in /dev/hidraw*; do
    printf "xLITE0" >"$d"
  done
}

kbd_backlight_on() {
  for d in /dev/hidraw*; do
    printf "xLITE6" >"$d"
  done
}

hid_bind() {
  echo 0003:03EB:2041.0002 >/sys/bus/hid/drivers/hid-generic/bind || :
  echo 0003:03EB:2042.0001 >/sys/bus/hid/drivers/hid-generic/bind || :
}

hid_unbind() {
  echo 0003:03EB:2041.0002 >/sys/bus/hid/drivers/hid-generic/unbind || :
  echo 0003:03EB:2042.0001 >/sys/bus/hid/drivers/hid-generic/unbind || :
}

case $1 in
  suspend)
    wifi_off
    hantro_off
    kbd_backlight_off
    hid_unbind
    ;;
  resume)
    kbd_backlight_on
    wifi_on
    hantro_on
    hid_bind
    ;;
  *)
    usage
    exit 1
    ;;
esac
