#!/bin/sh

PREFIX=
cachedir=$PREFIX/var/cache/icons/hicolor
icondir=$PREFIX/usr/share/icons/hicolor
pixmapsdir=$PREFIX/usr/share/pixmaps
pixmap48x48dir=$icondir/48x48/apps
pixmap32x32dir=$icondir/32x32/apps
pixmap16x16dir=$icondir/16x16/apps

pixmap_scale() {
    local orig="$1"
    local scale="$2"
    local to="$3"
    case "$orig" in 
	*.svg) 
	    # not implemented
	    return;;
	*)
	    mkdir -p `dirname $to`
	    # scale $orig at $scale as $to
	    convert -resize $scale $orig $to
    esac;
    ln -s $orig $to.orig
}

symlink_scaled() {
    local cachename="$1"
    local scalename="$2"
    mkdir -p `dirname "$scalename"`
    ln -s "$cachename" "$scalename"
}

# kill scaled files with broken .orig symlink
find $cachedir -follow -type l -name "*.orig" | while read brokenoriglink; do
    cachename=`echo $brokenoriglink | sed 's,.orig$,,'`
    rm -f "$cachename" "$brokenoriglink"
    echo rm -f "$cachename" "$brokenoriglink"
done

# check existing files for update
for scale in 48x48 32x32 16x16; do
    find $cachedir/$scale/apps -type l -name "*.orig" | while read orig; do
	cachename=`echo $orig |sed 's,.orig$,,'`
        # if orig is newer than cachename 
	if [ "$orig" -nt "$cachename" ]; then
	    pixmap_scale "$orig" $scale "$cachename"
	fi
    done
done

# cleanup of broken symlinks that point to /var/cache/icons/...
find $pixmap48x48dir $pixmap32x32dir $pixmap16x16dir $pixmapsdir -follow -type l -lname "$cachedir/*" -delete

find $pixmap48x48dir -type f | while read name; do
    for scale in 32x32 16x16; do
	scalename=`echo $name | sed -e "s,48x48,$scale,"`
	cachename=`echo $scalename | sed -e "s,^$icondir,$cachedir,"`
	if [ ! -e "$cachename" ] && [ ! -e "$scalename" ]; then 
	    pixmap_scale "$name" $scale "$cachename"
	    symlink_scaled "$cachename" "$scalename"
	fi
    done
done

find $pixmap32x32dir -type f | while read name; do
    for scale in 16x16; do
	scalename=`echo $name | sed -e "s,32x32,$scale,"`
	cachename=`echo $scalename | sed -e "s,^$icondir,$cachedir,"`
	if [ ! -e "$cachename" ] && [ ! -e "$scalename" ]; then 
	    pixmap_scale "$name" $scale "$cachename"
	    symlink_scaled "$cachename" "$scalename"
	fi
    done
done

# -maxdepth 0: too many garbage is stored in pixmapsdir :(
find $pixmapsdir -maxdepth 0 -type f | while read name; do
    for scale in 32x32 16x16; do
	scalename=`echo $name | sed -e "s,$pixmapsdir,$icondir/$scale/apps,"`
	cachename=`echo $scalename | sed -e "s,^$icondir,$cachedir,"`
	if [ ! -e "$cachename" ] && [ ! -e "$scalename" ]; then 
	    pixmap_scale "$name" $scale "$cachename"
	    symlink_scaled "$cachename" "$scalename"
	fi
    done
done
