#!/bin/bash
#
# /usr/local/bin/set_screen_timeout
#
# Sets the timeout to turn off screen via xautolock.
# (xautolock has been compiled to call "xset dpms force off")
# We do this both in the icewm startup file as well as for the current 
# session (by killing and restarting xautolock with new time value)
#
# Copyright 2013-2016  by Paul Sherman, GPL3

# first, lets make sure we're running a laptop or something with a battery
# if no battery is detected an empty string is returned, 
# so send message to user and bail...
notbat=$(acpi  2>/dev/null)
if [ -z "$notbat" ]; then
	yad --center --timeout=10 --window-icon="/usr/share/pixmaps/clock.xpm" --title "Timeout Set" --button="gtk-ok:0" --width 300 --text="\n    The screen off timer is for use   \n    with battery-operated machines.   \n    (As a power-saving feature.)    \n\n    You do not seem to have a battery...    \n"
	exit 0
fi

# settings file (icwewm startup)
icewm_startup_file="$HOME/.icewm/startup"


# use a simple dialog to let the user choose a screen timeout in minutes.
x=`yad --center --window-icon="/usr/share/pixmaps/clock.xpm" --image="/usr/share/pixmaps/screen.png" --scale --title='Set Screen Timeout' --text='\n     Set how many minutes before your screen \n              is turned off to save power. \n\n\n   A value of \"0\" disables turning off the screen.     \n' --value=5 --min-value=0 --max-value=50 --step=5`


# bail if the user clicks cancel
if [ -z "$x" ]; then
    exit 0
fi


# If value set to "0" (meaning to disable)
# we kill xautolock as well as remove call from icewm startup file.
if [ "$x" = "0" ]; then
	killall -9 xautolock
	sed -i '/\/usr\/local\/bin\/xautolock/d' $icewm_startup_file
	yad --center --timeout=4 --window-icon="/usr/share/pixmaps/clock.xpm" --title "Timeout Set" --button="gtk-ok:0" --width 300 --text="    Timer to turn off your screen   \n    has been removed.  "
    exit 0
fi


# string we will be entering into the icewm startup file
str="/usr/local/bin/xautolock -time $x 2>/dev/null&"


# delete the old line in icewm startup file, if not there send error to /dev/null, so who cares...
sed -i '/\/usr\/local\/bin\/xautolock/d' $icewm_startup_file 2>/dev/null
# write new line...
echo "$str" >> $icewm_startup_file
	

# then go ahead and set the timeout for the current session:
killall -9 xautolock 2>/dev/null
/usr/local/bin/xautolock -time $x 2>/dev/null&


# tell the user the good news
yad --center --timeout=4 --window-icon="/usr/share/pixmaps/clock.xpm" --title "Timeout Set" --button="gtk-ok:0" --width 300 --text="    Timer to turn off your screen   \n    has been set to $x minutes.  "
exit 0
