saturnin_zleep.sh 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/bin/bash
  2. ffoo import inigrep
  3. ffoo import pretty
  4. ffoo import sync
  5. __zleep_user_part() {
  6. saturnin iam undocking
  7. slock &
  8. }
  9. __zleep_try_umount() {
  10. local mp=$1
  11. mountpoint -q $mp || return 0
  12. umount $mp || return 1
  13. mount | grep $mp && return 1
  14. return 0
  15. }
  16. __zleep_try_umount_all() {
  17. local mp
  18. for mp in $(inigrep -p iam.mounting.point);
  19. do
  20. __zleep_try_umount $mp || return 1
  21. done
  22. return 0
  23. }
  24. __zleep_sudo_part() {
  25. wait_until -d 5 -t 30 __zleep_try_umount_all || die "unable to unmount drives"
  26. pm-suspend
  27. }
  28. __zleep_sudo_part_started() {
  29. # i.e. password prompt went ok
  30. test -e $ZLEEP_ON_ROOT
  31. rv=$?
  32. debug -v rv
  33. return $rv
  34. }
  35. __zleep_user_part_done() {
  36. ! test -e $ZLEEP_ON_USER
  37. rv=$?
  38. debug -v rv
  39. return $rv
  40. }
  41. __zleep_min_path() {
  42. echo -n $(sudo env | grep ^PATH)
  43. echo -n :
  44. echo -n $(dirname $(which ffoom))
  45. echo -n :
  46. echo -n $(dirname $(which saturnin))
  47. }
  48. zleep() {
  49. #
  50. # Put the host on sleep
  51. #
  52. # We need to
  53. #
  54. # 1. authenticate
  55. # 2. start user's part in the background -- mainly slock
  56. # 3. start root's part -- put system on sleep (unmount, suspend)
  57. #
  58. # This is solved by forking with sudo, and waiting for user part to indicate
  59. # it has finished. That way, we can ensure that suspend happens *after* the
  60. # screen has been locked, and at the same time we leave authentication part
  61. # on sudo.
  62. #
  63. if test -z "$ZLEEP_ON_USER"; ## we are parent (running as normal user)
  64. then
  65. ZLEEP_ON_USER=$(mktemp)
  66. ZLEEP_ON_ROOT=$(mktemp -u)
  67. SUDO_PATH=$(__zleep_min_path) # needed while bins are still under local
  68. debug -v ZLEEP_ON_USER ZLEEP_ON_ROOT SUDO_PATH
  69. sudo env \
  70. ZLEEP_ON_ROOT=$ZLEEP_ON_ROOT \
  71. ZLEEP_ON_USER=$ZLEEP_ON_USER \
  72. PATH=$SUDO_PATH \
  73. saturnin iam zleeping &
  74. wait_until -t 60 __zleep_sudo_part_started # i.e. password prompt done
  75. __zleep_user_part
  76. rm -f $ZLEEP_ON_USER
  77. else ## we are child (running as root)
  78. touch $ZLEEP_ON_ROOT
  79. test $(id -u) -eq 0 || die "must be root"
  80. wait_until __zleep_user_part_done || die "timeout waiting for parent"
  81. __zleep_sudo_part
  82. rm -f $ZLEEP_ON_ROOT
  83. return $?
  84. fi
  85. }