hd-usb.sh 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/bin/sh
  2. # dependencies:
  3. # mount grep readlink hdparm whoami
  4. [ "$(whoami)" != "root" ] && echo "Sorry, you must have root privileges to run this script" && exit 1
  5. # These _must_ be defined outside the script
  6. [ -z "$node" ] && echo "You must export \$node variable!" && exit 1
  7. [ -z "$hdparm_device" ] && echo "You must export \$hdparm_device variable!" && exit 1
  8. basepath="/sys/bus/usb"
  9. bind_file="$basepath/drivers/usb/bind"
  10. unbind_file="$basepath/drivers/usb/unbind"
  11. autosuspend_file="$basepath/devices/$node/power/autosuspend_delay_ms"
  12. control_file="$basepath/devices/$node/power/control"
  13. restore_autosuspend="${restore_autosuspend:-2000}" # default value
  14. restore_control="${restore_control:-on}" # default value
  15. case "$1" in
  16. off)
  17. # Must not be mounted
  18. if [ -r "$hdparm_device" ]; then
  19. mount | grep "^$(readlink -f "$hdparm_device")" && echo "Must not be mounted!" && exit 1
  20. # First, send it to sleep.
  21. /usr/bin/hdparm -Y "$hdparm_device" || exit 1 # systemd unit will retry on fail
  22. fi
  23. # echoing states
  24. echo "Before:"
  25. printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
  26. printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
  27. # stackoverflow.com/a/12675749
  28. echo "0" > "$autosuspend_file" || exit 1
  29. echo "auto" > "$control_file" || exit 1
  30. echo "After:"
  31. printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
  32. printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
  33. # stackoverflow.com/a/18098075
  34. echo "$node" > "$unbind_file" && echo "Unbinding $node succeeded." || echo "Unbinding $node failed, but that's not necessarily a problem. Please investigate."
  35. exit 0
  36. ;;
  37. on)
  38. # Waking it up in reverse order
  39. echo "$node" > "$bind_file" && echo "Binding $node succeeded" || echo "Binding $node failed, but that's not necessarily a problem. Please investigate."
  40. # echoing states
  41. echo "Before:"
  42. printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
  43. printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
  44. # Action
  45. echo "$restore_autosuspend" > "$autosuspend_file" || exit 1
  46. echo "$restore_control" > "$control_file" || exit 1
  47. ###############################################
  48. echo "After:"
  49. printf "%s: %s\n" "$autosuspend_file" "$(cat "$autosuspend_file")"
  50. printf "%s: %s\n" "$control_file" "$(cat "$control_file")"
  51. # There's no need to wake the device up with hdparm; it will do so when accessed, albeit with a delay.
  52. exit 0
  53. ;;
  54. *)
  55. echo "Wrong argument $1"; exit 1
  56. ;;
  57. esac >&2