#!/bin/sh
# $Id: reduce_xpm_colors,v 3.1.1.1 1996/03/27 16:44:42 deejai!martin Exp $
#
# Give here a colon-separated list of all the directories
# where pixmap could reside (those which are needed by your fvwmrc):
XPM_PATH=$HOME/pix:$HOME/.icons:/usr/include/X11/pixmaps
#
# define the path to your fvwmrc
FVWMRC=$HOME/.fvwm2rc
#
# where is the pixy program?
PIXY=$HOME/BIN/pixy
#

#           --- Start of configuration check---
SCRIPT="\"`basename $0`\" script"
CONFIG_ERR=false
# Check for correct configuration.
if [ -z "$XPM_PATH" ] || [ ! -f $PIXY ] || [ ! -f $FVWMRC ]; then
    [ -z $XPM_PATH ] && echo >&2 "The \$XPMPATH path is not set correctly."
    [ ! -f $PIXY   ] && echo >&2 "The \$PIXY program path is not set correctly."
    [ ! -f $FVWMRC ] && echo >&2 "The \$FVWMRC fvwm config file's path is not set correctly."
    CONFIG_ERR=true
fi
for dir in `IFS=":$IFS"; echo $XPM_PATH`
do
    if [ ! -d $dir ]; then
	echo >&2 "\$XPM_PATH contains invalid directory $dir."
	CONFIG_ERR=true
    fi
done
# If any configuration error was detected, stop now.
if $CONFIG_ERR
then
    echo >&2 ""
    echo >&2 "You did not configure the $SCRIPT yet."
    exit 2
fi
#           --- End of configuration check---


# Check for correct usage:
BASEFILE=`eval echo '$'$#`
if [ $# -lt 1 ] || [ ! -f "$BASEFILE" ]; then
    echo >&2 "Usage:    `basename $0` [<options>] <base_xpm_file>"
    echo >&2 "Function: reduce the icons used in your fvwm script to"
    echo >&2 "          use only colors from the <base_xpm_file>."
    echo >&2 "          The new pixmap files are stored in the current directory."
    echo >&2 "Options:  These are passed to the pixy program, so see there for details"
    echo >&2 ""
    echo >&2 "Wrong number of arguments or invalid arguments given"
    exit 1
fi

# Enabling this will show you the file names that would be converted:
# tr "\"%* ,/" "\n\n\n\n\n\n" <$FVWMRC | grep '\.xpm' | sort -u | tr '\n' '\t'; echo ""

# Sanity check: (accounting for possible symlinks)
if [ `pwd` = `cd $SYSXPM; pwd` ] || [ `pwd` = `cd $MY_XPM; pwd` ]; then
    echo >&2 "We don't want to overwrite your precious icons, do we?  ;-)"
    echo >&2 "The $SCRIPT will not run if started"
    echo >&2 "from the \$SYSXPM or \$MY_XPM directory."
    echo >&2 "See the $SCRIPT for details."
    exit 1
fi

# Start of the conversion:
tr "\"%* ,/" "\n\n\n\n\n\n" <$FVWMRC | grep '\.xpm' | sort -u |
while read ico
do
  inp=""
  for dir in `IFS=":$IFS"; echo $XPM_PATH`
  do
    if [ -r $dir/$ico ]; then
      inp=$dir/$ico
      break
    fi
  done
  if [ -f "$inp" ]; then
    echo "Doing $ico  (from $dir)"
    $PIXY -o $ico "$@" $inp
  else
    echo "No such icon: " $ico
    continue
  fi
done
echo Done.
