The system's sleep function is a great feature; it works stably and saves a lot of time rebooting the system. The problem is, when sleep is enabled, you have the risk that the system goes to sleep when it shouldn't, e.g. during a big download or backup. So the best solution would be for the sleep function to be deactivated when a user is logged in, and activated when nobody is logged in.
So I wrote two small shell scripts, called by the login and logout hooks. Because OS X is a multi user OS, you have to consider that more then one user can login and logout. Therefore, the sleep timer must be activated only when the last user loged out of the system.
Here is the login script login.sh:
#!/bin/sh
#
# create login lock
echo $1 > /tmp/login_$1.LOCK
# deactivate system sleep timer
/usr/bin/pmset -a sleep 0
And the logout script logout.sh:
#!/bin/sh
#
# delete own login lock
rm /tmp/login_$1.LOCK
# test other user is logged in
if [ ! -s /tmp/login_*.LOCK ]
then
# no other login lock found, activate system sleep timer
/usr/bin/pmset -a sleep 15
fi
The login script is setting a LOCK file, created with the user name, then it deactivates the sleep timer. The logout script is deleting the user's own LOCK file. Then it tests for other user LOCK files, and when no LOCK files are found, then it activates the sleep timer for 15 minutes. To get the two scripts executed when login/logout occurs, activate them as follow:
sudo defaults write com.apple.loginwindow LoginHook /path/to/script/login.sh
sudo defaults write com.apple.loginwindow LogoutHook /path/to/script/logout.sh
Two simple scripts let you implement a system sleep management.
Mac OS X Hints
http://hints.macworld.com/article.php?story=20050102120718523