#!/bin/bash
#
# setup-background copyright 1999 Lars Wirzenius
# modified and copyrighted by Julian Gilbey <jdg@debian.org>, 1999.
# This program is licensed under the GNU General Public License,
# Version 2 or later.
# No warranty of any kind is implied.
# 
# Set the X root window to what the user prefers.
#
#	if ~/.wm-common/background.xpm exists,
#    do xpmroot for it,
#	else if ~/.wm-common/background.{gif,jpg} exists,
#    do xsetbg for it,
#	else if ~/.wm-common/background.color exists,
#    do xsetroot -solid for it,
#	else if ~/.wm-common/background.list exists,
#    do xsetbg for a random line from it,
#
# If none of these exist, try /etc/X11/wm-common/background.*

# ------------ Functions and setup
available()
{
  command -v $1 1>/dev/null 2>&1
}

if available xsetbg; then
  viewer=xsetbg
elif available xv; then
  viewer="xv -root -quit"
else
  viewer="exit 1;"
fi

if available xpmroot; then
  xpmroot=xpmroot
else
  xpmroot="exit 1;"
fi

if available xsetroot; then
  xsetroot=xsetroot
else
  xsetroot="exit 1;"
fi

randline()
{
  filename=$1

  set `wc -l $filename`
  lines=$1

  line=$(( ( $RANDOM % $lines ) + 1 ))

  sed -n "${line}p" $filename
}


# ------------ Main script
## We no longer look in an fvwm subdirectory, as we are intending to make
## this script become window-manager independent.
##
## # Note that PKG should be fvwm even if this is for FVWM 2.2, as the fvwm
## # package now lives in directories named fvwm.
## if [ "x$1" != "x" ]
## then
## 		 PKG=$1
## else
## 		 PKG="fvwm"
## fi

personal_dir=~/.wm-common
system_dir=/etc/X11/wm-common

xpmfile=background.xpm
giffile=background.gif
jpgfile=background.jpg
colorfile=background.color
listfile=background.list
 
if [ -d "$personal_dir" ] && cd "$personal_dir"
then
  [ -r $xpmfile -a -s $xpmfile ] && $xpmroot $xpmfile && exit 0
  [ -r $giffile -a -s $giffile ] && $viewer $giffile && exit 0
  [ -r $jpgfile -a -s $jpgfile ] && $viewer $jpgfile && exit 0
  [ -r $colorfile -a -s $colorfile ] && $xsetroot -solid `cat $colorfile` \
    && exit 0
  [ -r $listfile -a -s $listfile ] && $viewer `randline $listfile` && exit 0
fi

if [ -d "$system_dir" ] && cd "$system_dir"
then
  [ -r $xpmfile -a -s $xpmfile ] && $xpmroot $xpmfile && exit 0
  [ -r $giffile -a -s $giffile ] && $viewer $giffile && exit 0
  [ -r $jpgfile -a -s $jpgfile ] && $viewer $jpgfile && exit 0
  [ -r $colorfile -a -s $colorfile ] && $xsetroot -solid `cat $colorfile` \
    && exit 0
  [ -r $listfile -a -s $listfile ] && $viewer `randline $listfile` && exit 0
fi

exit 0
