#!/bin/bash

# scale-backgrounds: scales down and converts the images for wmbackground

SourceDirectory="`pwd`"

TargetDirectory="$HOME/.wmbackground"

if [ "`ps ax | grep 'wmbackground' | grep -v 'grep'`" != "" ]
then
    echo
    echo "Killing wmbackground..."
    killall wmbackground
fi

echo
echo "Preparing background files..."

for source_file in *.gif *.GIF *.jpg *.JPG *.jpeg *.JPEG *.tif *.TIF *.tiff *.TIFF
do
    destination_file="`echo $source_file | sed -E 's/\.(gif)?(jpg)?(jpeg)?(tif)?(tiff)?(GIF)?(JPG)?(JPEG)?(TIF)?(TIFF)?/.png/'`"
    if [ -f "$source_file" ] && [ ! -f "$destination_file" ]
    then
	echo "$source_file --> $destination_file"
	convert "$source_file" "$destination_file"
    fi
done

for source_file in *.PNG
do
    destination_file="`echo $source_file | sed 's/\.PNG/.png/'`"
    if [ -f $source_file ] && [ ! -f "$destination_file" ]
    then
	echo "$source_file --> $destination_file"
	cp -p "$source_file" "$destination_file"
    fi
done

for file in "$SourceDirectory"/*.png
do
    if [ -e "$file" ]
    then
	break
    fi
    echo
    echo "There's no *.png file in the $SourceDirectory directory."
    exit
done

if [ ! -d "$TargetDirectory" ]
then
    echo
    echo "Making the $TargetDirectory directory..."
    mkdir "$TargetDirectory"
fi

echo
echo "Copying background files to the $TargetDirectory directory..."

if [ "$SourceDirectory" != "$TargetDirectory" ]
then
	for file in $SourceDirectory/*.png
	do
	    file="`echo $file | sed 's#.*/##'`"
	    echo "$SourceDirectory/$file --> $TargetDirectory/$file"
	    cp -p $SourceDirectory/$file $TargetDirectory
	done
	
fi

echo
echo "Preparing miniature and configuration files..."

cd "$TargetDirectory"

for source in *.png
do
	destination=`echo $source | sed "s#\.png##"`
	echo "$source --> $destination.xpm.gz"
	touch "$destination"
	nice -n 19 montage "$source" -background gray -colors 256 -geometry 54x54 -size 54x54 -unsharp 0.125 +adjoin "$destination.xpm.gz"
done

