Last active
January 17, 2020 18:20
-
-
Save Canx/9d2c63430eb563d50960fa31670538a1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# TODO: comprobar que xprintidle está instalado. | |
USER="" | |
DISPLAY="" | |
check_xprintidle() { | |
if [ $(dpkg-query -W -f='${Status}' xprintidle 2>/dev/null | grep -c "ok installed") -eq 0 ]; | |
then | |
apt-get install xprintidle; | |
fi | |
} | |
get_displays() { | |
declare -A disps usrs | |
usrs=() | |
disps=() | |
for i in $(users);do | |
[[ $i = root ]] && continue # skip root | |
usrs[$i]=1 | |
done # unique names | |
for u in "${!usrs[@]}"; do | |
for i in $(sudo ps e -u "$u" | sed -rn 's/.* DISPLAY=(:[0-9]*).*/\1/p');do | |
disps[$i]=$u | |
done | |
done | |
for d in "${!disps[@]}";do | |
USER=${disps[$d]} | |
DISPLAY=$d | |
logger "User: $USER, Display: $DISPLAY" | |
export DISPLAY=$DISPLAY | |
done | |
} | |
# TODO: if check_xprintidle gives error we should not continue. | |
check_xprintidle | |
get_displays | |
minutos=${1:-30} | |
FILENAME="shutdown_when_idle.sh" | |
cp $0 /usr/local/bin/$FILENAME | |
chown root:root /usr/local/bin/$FILENAME | |
CRON_FILENAME="shutdown" | |
FILE="/etc/cron.d/$CRON_FILENAME" | |
if [ ! -f $FILE ]; then | |
echo "SHELL=/bin/bash" > /tmp/$CRON_FILENAME | |
echo "*/1 * * * * root /usr/local/bin/$FILENAME" >> /tmp/$CRON_FILENAME | |
mv /tmp/$CRON_FILENAME /etc/cron.d/ | |
chown root:root /etc/cron.d/$CRON_FILENAME | |
fi | |
idletime=$((60*1000*$minutos)) | |
idle=`sudo -u $USER env DISPLAY=$DISPLAY /usr/bin/xprintidle` | |
# This creates a date file used when no user is logged in | |
if [ -z $idle ]; then | |
if [ -f /tmp/idle ]; then | |
idle=`cat /tmp/idle` | |
else | |
idle=0 | |
fi | |
idle=$((idle+60000)) | |
echo $idle > /tmp/idle | |
else | |
rm -rf /tmp/idle | |
fi | |
logger "Comprobando si han pasado $minutos minutos de inactividad." | |
if [[ $idletime -lt $idle ]]; then | |
logger "apagamos el ordenador" | |
/sbin/shutdown -P now | |
else | |
logger "no apagamos aun. Faltan $((($idletime-$idle)/60000)) minutos." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment