#!/bin/bash
#
# 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.

shopt -s extglob

readonly SAVER_DIR=/usr/lib/xscreensaver

function allsavers() {
  printf "%b" "$(
    xrdb -n ~/.xscreensaver 2>/dev/null |\
    grep ^programs: |\
    cut -d : -f 2-
  )"
}

random_saver=
(( random_count = 0 ))
while IFS= read -r saver; do
  saver=${saver##*([[:space:]])}
  # Skip disabled savers.
  case "${saver}" in
    -*)
      continue
      ;;
  esac
  # Strip visual name.
  saver=${saver##*([^[:space:]:\"]):*([[:space:]])}
  # Strip hack name.
  saver=${saver##\"*([^\"])\"*([[:space:]])}
  # Does it exist?
  saver=${SAVER_DIR}/${saver}
  [[ -f ${saver%% *} ]] || continue
  # Rest is the command line!
  (( ++random_count ))
  if (( RANDOM % random_count == 0 )); then
    random_saver=${saver}
  fi
done < <(allsavers)

if [[ -z ${random_saver} ]]; then
  xset s activate
  sleep 1
  exit
fi

eval "exec ${random_saver}"
