#!/bin/bash
#######################################################
# sleeptimer for PCLinuxOS                            #
# Author: D.M-Wilhelm (Leiche)                        #
# Co-Author: embi, Manfred (Maintainer of fluxflux)   #
# Email: kellerleicheorig at aol.com                  #
# Licence: GPL                                        #
# First build: Aug Mon 02 2010                        #
# Last build:  Mar Tue 09 2021                        #
# fixed icon display in systray, to move zenity,      #   
# based now on yad.                                   #
# Special thanks goes to Neal Brooks                  #
#######################################################
#
Encoding=UTF-8
#
# i18n - Internationalization - Internationalisierung
#
export TEXTDOMAIN=sleeptimer
export TEXTDOMAINDIR="/usr/share/locale"
#
# define some variables - Definierung einiger Variablen 
#
TITLE=sleeptimer
VERSION=0.76
ICON=/usr/share/icons/sleeptimer.png
TIME=`date +%H:%M`
DATE=`date +%Y-%m-%d`
#
# set your Distro name - gib dein Distroname an
#
DISTRO=PCLinuxOS
#
# create a fake file - eine Fake Datei erstellen
#
if ! test -d ~/.config/sleeptimer  ; then
mkdir -p ~/.config/sleeptimer
echo 15 > ~/.config/sleeptimer/minutes
fi 
CONF_DIR=$HOME/.config/sleeptimer
#
# check is sleeptimer running - prüfen ob sleeptimer läuft
#
if [ `ps -e | grep -c sleeptimer`  -gt 2 ] ; then
	yad --image=$ICON \
	--title=$TITLE --timeout 30 --window-icon=$ICON \
	--text=$"   		  <b>- Sleeptimer are running!-</b> \n
	<b>Your computer will shutdown at `cat ~/.config/sleeptimer/timestamp`</b> \n
	Do you want to cancel the countdown?"
			if [ $? = "0" ]; then 
				killall sleeptimer
				else
				exit 0
			fi	
fi	


function configure_settings() 
{
#	
# read current settings - Einstellungen lesen
# 
if [ $(grep -c "wait for:true" $CONF_DIR/conf.cfg) -gt 0 ]; then
	RUN_S=true
	else
	RUN_S=false
fi
if [ $(grep -c "exit:true" $CONF_DIR/conf.cfg) -gt 0 ]; then
	CLS_S=true
	else
	CLS_S=false
fi
if [ -f /usr/bin/pm-suspend ]; then
	PM_SUSPEND="<item>pm-suspend|PM-Suspend</item>"
	PM_HIPERNATE="<item>pm-hibernate|PM-Hibernate</item>"
fi
if [ $(grep -c "Hibernate" $CONF_DIR/conf.cfg) -gt 0 ]; then
	TASK_S=Hibernate
elif [ $(grep -c "Suspend" $CONF_DIR/conf.cfg) -gt 0 ]; then	
	TASK_S=Suspend
elif [ $(grep -c "pm-suspend" $CONF_DIR/conf.cfg) -gt 0 ]; then	
	TASK_S=PM-Suspend
elif [ $(grep -c "pm-hipernate" $CONF_DIR/conf.cfg) -gt 0 ]; then	
	TASK_S=PM-Hibernate
elif [ $(grep -c "Stop" $CONF_DIR/conf.cfg) -gt 0 ]; then	
	TASK_S=Shutdown
else
	TASK_S=None
fi

#
export SETTINGS_DIALOG='
<window window_position="1" title="'$TITLE' '$VERSION'" resizable="true" icon-name="sleeptimer">
<vbox>
	<frame>
		<vbox>
			<text xalign="0" selectable="false" use-markup="True">
				<label>"<b>'$"Don't shut down if running"'</b>"</label>
			</text>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"'$"Wait on active programs, like Mplayer, Mencoder and FFMPEG.
As soon as these programs have finished their jobs Sleeptimer
will shut down. Do you want to enable it?"'"</label>
			</text>
			<checkbox  active="'$RUN_S'">
				<label>'$"Enable"'</label>
				<variable>RUN</variable>
			</checkbox>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"'$"<b>Note:</b> Only those independently supported programs will be terminated.."'"</label>
			</text>	
		</vbox>	
		<hseparator></hseparator>
		<vbox>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"<b>'$"What should sleeptimer do"'</b>"</label>
			</text>
			<tree column-visible ="false|true" space-fill="true" allow-shrink="true" selected-row="0">
				<variable>END</variable>
				<label>|'$"Select a task                        "'</label>
				<item>dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop|Shutdown</item>
				<item>dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Suspend boolean:true|ConsoleKit Suspend</item>
				<item>dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit" /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Hibernate boolean:true|ConsoleKit Hipernate</item>
				'$PM_SUSPEND'
				'$PM_HIPERNATE'
			</tree>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"'$"Selected is <b>"$TASK_S"</b>"'"</label>
			</text>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"'$"<b>Note:</b> You must choose every time your favorite task. Default will use shutdown by clicking save."'"</label>
			</text>
			<hseparator></hseparator>	
			<text xalign="0" selectable="false" use-markup="True">
				<label>"<b>'$"Close QMPlay2"'</b>"</label>
			</text>
			<text xalign="0" selectable="false" use-markup="True" width-chars="80">
				<label>"'$"Close QMPLay2 before the system will shutdown. Do you want to enable it?"'"</label>
			</text>
			<checkbox  active="'$CLS_S'">
				<label>'$"Enable"'</label>
				<variable>CLS</variable>
			</checkbox>	
		</vbox>
		<hseparator></hseparator>
	</frame>	
	<hbox start="true">
		<hbox start="true">
			<button>
				<label>"'$" Save "'"</label>
				<input file icon="document-save"></input>
				<action type="exit">save</action>
			</button>	
			<button>
				<label>"'$"Close"'"</label>
				<input file icon="exit"></input>
				<action type="exit">close</action>
			</button>
		</hbox>
	</hbox>
</vbox>
</window>
'

I=$IFS; IFS=""
for STATEMENT in  $(gtkdialog --center --program=SETTINGS_DIALOG); do
	eval $STATEMENT
done
IFS=$I

if [ "$EXIT" == "save" ];then
echo -e "#Configuration file for sleeptimer.\nwait for:$RUN\nexit:$CLS\nend:$END"| \
sed -e '/^\s*$/d' > $CONF_DIR/conf.cfg
fi

}
#
#check status of sleeptimer
#
if [ $(grep -c "end:" $CONF_DIR/conf.cfg) -lt 1 ]; then 
yad --title $"$TITLE""$VERSION" \
                --button="gtk-ok:0" \
                --width 300 \
                --window-icon=$ICON \
                --image=$ICON \
                --text=$"<b>Looks like sleeptimer is started first time.</b> \nPlease choose in the settings how the system should be shutdown."
                configure_settings
fi
#
#question - Frage
#
function menu {
	COUNTDOWN=$(yad --image=$ICON --scale \
					--text=$"$TIP\n<b>Set the time (in minutes) to shutdown your system:</b>" \
					--value=$(cat ~/.config/sleeptimer/minutes) \
                    --min-value=0 --max-value=300 --step=5 \
					--title="$TITLE"" $VERSION" --window-icon=$ICON \
					--button="gtk-about:2" \
					--button="gtk-preferences:3" \
					--button="gtk-ok:0" \
					--button="gtk-close:1" \
				)
	ret=$?

	[[ $ret -eq 1 ]] && exit 0
#
#about - Über
#
	if [[ $ret -eq 2 ]]; then
		yad --image=$ICON \
	--title=$"About" --timeout 30 --window-icon=$ICON \
	--text=$"     <b>- Sleeptimer -</b> \n
	<b>Author:</b> D.M.-Wilhelm (Leiche)\n
	<b>Co-Authors:</b> embi, and Manfred \n
	The sleeptimer is a shutdown tool for PCLinuxOS \n
	Sleeptimer is also ported to flux-flux by embi \n
	and Manfred (<b>Maintainer</b> of fluxflux) \n
	<b>Version:</b> $VERSION  \n
	<a href='http://kellerleiche.bplaced.net/index/sleeptimer.html'>More about Sleeptimer</a>\n
	<b>Special thanks</b> goes to Neal Brooks."
		menu
	fi

	if [[ $ret -eq 3 ]]; then
		configure_settings	
		menu	
	fi
}
	menu
#	
# exit - schließen
#
	function Exit () 
	{ 
		yad --title="sleeptimer" \
			--window-icon="/usr/share/icons/sleeptimer.png" \
			--text $"Sure to abort countdown?"
			if [ $? = "0" ]; then 
				killall sleeptimer
			fi
	} 
	export -f Exit
#	
# progress - ausführen
#
	if [ "$COUNTDOWN" = "" ];then
		exit
	else
		echo $COUNTDOWN > ~/.config/sleeptimer/minutes
		TIMER=$(echo $(($COUNTDOWN*60)))
		TASK1=$(date  +%T -s "+$TIMER seconds" 2>/dev/null)
		echo $TASK1 > ~/.config/sleeptimer/timestamp
		exec 3> >(yad --title $TITLE --notification --image=$ICON --listen --icon-size="128"\
					  --command='yad --title '"$TITLE"' \
					  --text "<b>'$"Your computer will shutdown at $TASK1!"'</b>" \
					  --window-icon='$ICON' --button="gtk-close:0" \
					  --width=400 --form --field '$"Exit:btn"' \
				  "sh -c Exit"'
				 )
		echo tooltip: $"Your computer will shutdown at $TASK1!" >&3
#		
#sleep $TIMER
#
	while [ $TIMER -ge 1 ]
	do
	sleep 1
   TIMER=$[$TIMER-1]
	done
	exec 3>&-
#
#check for running players, or encoders - prüfen auf laufende Players 
# oder Encoders
#
	if [ $(grep -c "wait for:true" $CONF_DIR/conf.cfg) -gt 0 ];then
		while [ "`ps -e | grep -w mplayer`" ]; do sleep 60|yad --text $"Mplayer not finish, waiting... " \
		--no-buttons --timeout=5 --undecorated --geometry=100x50+10+30 --window-icon=$ICON --title="$TITLE"" $VERSION"; \
		done; echo $"mplayer not running or done"
		while [ "`ps -e | grep -w mencoder`" ]; do sleep 60|yad --text $"Mencoder not finish, waiting..." \
		--no-buttons --timeout=5 --undecorated --geometry=100x50+10+30 --window-icon=$ICON --title="$TITLE"" $VERSION"; \
		done; echo $"mencoder not running or done"
		while [ "`ps -e | grep -w ffmpeg`" ]; do sleep 60|yad --text $"FFMPEG not finish, waiting..." \
		--no-buttons --timeout=5 --undecorated --geometry=100x50+10+30--window-icon=$ICON --title="$TITLE"" $VERSION"; \
		done; echo $"ffmpeg not running or done"
	fi
#
#last change to exit - letzte Möglichkeit den Countdown zu stoppen
#
(
		for i in {99..2}; do
		echo $i ; sleep 0.14
		done
		echo "1" ; sleep 0.14 ) |
        yad --progress \
			--window-icon=$ICON \
			--title $"$TITLE""$VERSION" \
			--text=$"Your system will shutdown in 20 seconds.\n<b>To abort click on close!</b>" \
			--percentage=0 \
			--auto-close \
			--button="gtk-close:1" 
		if [ "$?" = 1 ] ; then
			yad --title $"$TITLE""$VERSION" \
                --button="gtk-ok:0" \
                --width 300 \
                --window-icon=$ICON \
                --text=$"Aborted by user!"
            exit
        fi
#
#shutdown - Herunterfahren
#	
	if [ "`ps -e | grep -w QMPlay2`" ]; then
		if [ $(grep -c "exit:true" $CONF_DIR/conf.cfg) -gt 0 ]; then
		QMPlay2 --quit
		sleep 1
		fi
	fi	
	`grep end $CONF_DIR/conf.cfg | cut -d ":" -f2-3`	
fi
exit
