#!/bin/sh
# Convert IceWM Icons from KDE's
# This script requires ImagemagicK
#

# Global variables
if [ "$UID" = "0" ]; then
  BASEDIR="/usr/share/icons"
else
  BASEDIR="$HOME/.icons"
fi
SIZE="48x48"

# substitute a theme
# vars: THEMEDIR, DEFAULT, SIZES 
mtheme()
{
  BASENAME=`basename $THEMEDIR`
  if [ -L $THEMEDIR -a "$BASENAME" = "default" ]; then
     echo Skipping default
     return 0  
  fi

  TARGET=$BASEDIR/$BASENAME-Ice
  mkdir -p $TARGET
  if [ ! $? = 0 ]; then
     echo Can not create $TARGET, FAILED !
     return
  fi
  echo Converting $TARGET ...
  for ICON in $THEMEDIR/$SIZE/apps/*.png ; do
     NAME=`basename $ICON .png`
     [ ! -f $TARGET/${NAME}_32x32.xpm ] && convert $ICON -resize 32x32 $TARGET/${NAME}_32x32.xpm
     [ ! -f $TARGET/${NAME}_16x16.xpm ] && convert $ICON -resize 16x16 $TARGET/${NAME}_16x16.xpm
     echo -n .
  done
  echo
  echo "#Converted from KDE Icon theme by iconicewm" > $TARGET/index.icewm
  echo "[IceWM Icon Theme]" >> $TARGET/index.icewm
  NAME=`grep -e "^Name=" $THEMEDIR/index.desktop`
  echo "$NAME converted for IceWM" >> $TARGET/index.icewm
  grep -e "^Comment=" $THEMEDIR/index.desktop >> $TARGET/index.icewm
}

show_help()
{
echo "Usage: iconicewm [[kde_icons] [ice_icons]"
echo "Convert KDE icon theme to IceWM icons"
echo 
echo "Example"
echo "iconicewm"
echo "   convert all $BASEDIR/* to $BASEDIR/*-Ice"
echo
echo "iconicewm theme"
echo "   convert $BASEDIR/theme to $BASEDIR/theme-Ice"
exit 0
}

######################################################################
# Main program

[ "$1" == "-h" ] && show_help
[ "$1" == "--help" ] && show_help
if [ "$1" ]; then
   if [ "`dirname $1`" ]; then
      THEMEDIR=$1
   else
      THEMEDIR=$BASEDIR/$1
   fi
   grep -e "^[KDE Icon Theme]" $THEMEDIR/index.desktop > /dev/null
   if [ $? -gt 0 ]; then
      echo "$THEMEDIR is not a KDE icon theme"
      exit 1
   fi
   if [ "$2" ]; then
      if [ "`dirname $2`" ]; then
        DEFAULT=$2
      else
        DEFAULT=$BASEDIR/$2
      fi
   fi
   mtheme
   exit 0   
fi

# Merge all
find $BASEDIR -maxdepth 2 -name index.desktop -print | while read LINE; do
  grep -e "^[KDE Icon Theme]" $LINE > /dev/null
  if [ $? = 0 ]; then
    THEMEDIR=`dirname $LINE`
    mtheme
  fi
done
