autopoweroff Ubuntu

Automatic poweroff when idle

This worked on ubuntu 20.04

Install xprintidle

chmod u+s /sbin/shutdown

/etc/systemd/system/autopoweroff.service

[Unit]
Description=autopoweroff
After=multi-user.target

[Service]
User=USERNAME    <-- CHANGEME
ExecStart=/bin/bash /usr/local/bin/poweroff.sh

[Install]
WantedBy=multi-user.target

/usr/local/bin/poweroff.sh

#!/bin/dash
sleep 2
# get the X DISPLAY of the first logged-in user with a X session
DISPLAY="$(
  w --short --no-header \
    | awk '{ if( match($3, ":") ) { print $3; exit; } }'
)"
export DISPLAY
echo $DISPLAY

benchmark=7200000
while true; do 

idletime=$(xprintidle)
echo $idletime
if [ "$idletime" -gt "$benchmark" ]; then

  echo "larger"
  shutdown -P now
fi
sleep 1 
done
#sudo shutdown -P now
#shutdown -P 5
echo "end"