#!/bin/sh
# by Benjamin Okopnik <ben-fuzzybear@geocities.com>
# *** bkgr *** - A random background selector for XFree86

# Define the dir where the pictures are kept
PIC_DIR=/usr/share/Eterm/pix

# Create a unique tempfile name and save all PIC_DIR filenames into it
TMPFILE=$(mktemp /tmp/temp.XXXXXX)
ls $PIC_DIR/* > $TMPFILE 2> /dev/null

# A) Gen a random # (0 - 32767). B) Confine it to a range of (1 -
<picfile_count>). 
# C) Set $FNM to the filename on line $RANDOM in the $TMPFILE.
FNM=$(head -$(($RANDOM / (32768 / $(grep -c . $TMPFILE)) + 1)) $TMPFILE | tail
-1)

# This allows a pic name to be entered as an arg to bkgr - "Honey! You 
# should see this KEWL background that came up!" :) Anyway, check if the
# file exists (if an arg is entered) and substitute it for the random one.
if [ -f $PIC_DIR/$1 ]
then
    FNM=$PIC_DIR/$1
fi

# Tell me the name for future reference - or, provide a doublecheck if 
# I do enter an arg ("Yep, I'm using the pic that you specified.")
echo -n "Using "
basename $FNM

# Build in a 'wait-loop' to avoid a race condition with the WM -
# replace "icewm" with your own window manager's name.
while [ -z "$ICE" ]
do 
    ICE=$(ps ax | grep icewm)
    sleep 2
done

# Handle the pics differently based on size; I've found 20kB
# to be a good breakpoint for my JPGs and PNGs...

if [ $((`ls -al $FNM | awk '{print $5}'`)) -gt 20480 ]
then
    # Stretch to fit the root window...
    cat $FNM | xv -rmode 1 -max -quit - &
else
    # ...or tile the sucker.
    cat $FNM | xv -rmode 3 -quit - &
fi

# Clean up...
rm $TMPFILE

# ...and exit gracefully.
exit 0


# "Y'all come back now, y'hear?" :)

