#!/bin/sh
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Default settings of these variables.
: ${XSECURELOCK_BLANK_TIMEOUT:=600}     # Seconds; -1 disables blanking.
: ${XSECURELOCK_BLANK_DPMS_STATE:=off}  # Values: standby, suspend, off, on.

if [ "$XSECURELOCK_BLANK_TIMEOUT" -ge 0 ]; then
  # Wait 60 seconds before actually turning the screen off. Till then we have a
  # black background managed by xsecurelock's main process anyway.
  sleep "$XSECURELOCK_BLANK_TIMEOUT"

  # This function runs the following command in a SIGTERM-protected subshell.
  # This is used to avoid error spam from xset receiving SIGTERM.
  protect() {
    (
      trap '' TERM
      exec "$@"
    )
  }

  # This is run in a setsid'd background process so xsecurelock's SIGTERM doesn't
  # interrupt the xset operation.
  case "$XSECURELOCK_BLANK_DPMS_STATE" in
    standby|suspend|off)
      # Blank the screen, and turn it off with DPMS.
      protect xset s activate dpms force "$XSECURELOCK_BLANK_DPMS_STATE"
      ;;
    on)
      # Requesting the "on" DPMS state actually just disables DPMS use.
      protect xset s activate
      ;;
    *)
      echo >&2 "xsecurelock: XSECURELOCK_BLANK_DPMS_STATE not in standby/suspend/off/on."
      ;;
  esac
fi

# When actually blanking we usually won't get here as main.c will kill us in
# response to "xset s activate" - but just in case, sleep "forever". 1 day was
# chosen as sleep time to ensure savers get eventually restarted (just in case
# they may leak memory) while making this mechanism hard to notice by the user.
exec sleep 86400
