#!/bin/sh

#
#	Josef Kufner <jkufner@seznam.cz>
#
#	Tento script pocita kolikrat byl spusten
#	a pote spusti odpovidajici prikaz.
#
#	Pokud je spusten jako reakce na stisk 'power button',
#	umoznuje priradit tomuto cudliku az tri akce.
#
#

#============================================================================#
# Configuration:
#============================================================================#

counter_file="/var/run/twice2down/count"	# soubor pocitadla stisku
switch_file="/var/run/twice2down/disabled"	# soubor s povolenim funkce
timeout="0.6s"					# max. prodleva mezi stisky tlac.

# prikazy shellu poustene podle poctu stisku tlacitka
cmd_1="shutdown now -h"
cmd_2="shutdown now -r"
cmd_3a="lilo -R Windows_98"
cmd_3b="shutdown now -r"


#============================================================================#
# Code:
#============================================================================#

# pokud je zakazana cinnost tak zkoncime
if [ "1" = "`cat $switch_file 2> /dev/null`" ]
then
	exit
fi

#nejdrive pustime sami sebe na pozadi
if [ "$1" = "child" ]
then
	# inkrementujeme pocitadlo
	if [ ! -e "$counter_file" ]
	then
		echo -n "0" > $counter_file
		counter=0
	else
		counter=`cat $counter_file`
	fi
	counter=`expr $counter + 1`
	echo -n $counter > $counter_file
	
	# kontrola poctu stisku
	case "$counter" in
		"1" | "2" | "3")
			# ok, je to v poradku
			user_je_cvok="false"
			;;
		*)
			# user to prehnal, tak mu vynadame
			beep -r 1 -f 880 -d 100 -l 120 &
			user_je_cvok="true"		
			;;
	esac	



	# pockame jestli nebude prirustek do pocitadla
	LANG="" sleep $timeout				# LANG nuluju, aby to bralo desetinou
										# tecku a ne carku


	if [ "$counter" = "`cat $counter_file`" ] && [ "$user_je_cvok" != "true" ]
	then	
		# Tlacitko NEBYLO stisknuto:
		# vynulujem pocitadlo
		rm $counter_file
		
		# spustime prirazenou akci
		beep -r $counter -f 800 -d 100 -l 60
		case "$counter" in
			"1")
				$cmd_1
				;;
			"2")
				$cmd_2
				;;
			"3")
				$cmd_3a
				$cmd_3b
				;;
			*)
				# k tomu by nemelo dojit
				;;
		esac
		# a koncime
		exit 
	elif [ "$counter" = "`cat $counter_file`" ] && [ "$user_je_cvok" = "true" ]
	then
		# Tlacitko NEBYLO stisknuto, ale user je cvok:
		# vynulujem pocitadlo
		rm $counter_file
		exit
	else
		# Tlacitko BYLO stisknuto:
	
		# tak nemame uz co delat, udela to za nas nekdo jiny
		exit
	fi		
else
	$0 child &
fi

# vim: ts=4
