How can a script detect a user's idle time?

view story

http://askubuntu.com – I want to check, inside a bash script (*), how long the user of a X session has been idle. The user himself does not have to be using bash, but just X. If the user just moved the mouse, for example, a good answer would be "idle for 0 seconds". If he has not touched the computer in 5 minutes, a good answer would be "idle for 300 seconds" The reason to not use xautolock straight away is to be able to implement some complex behavior. For example, if the user is idle for 10 minutes, try to suspend, if he is idle for more 5 minutes, shutoff (I know it sounds odd, but suspend does not always work (HowTos)