#!/bin/bash

function call_inkscape {
    # $1: width = height
    # $2: source file (*.svg)
    # $3: target file (*.png)
    echo -n "$1x$1 "    
    
    if [ "$4" ==  "hicolor" ]; then        
        inkscape -D -w $1 -h $1 $2 --export-png=./hicolor/$1x$1/apps/$3 >/dev/null 2>&1
    else
        inkscape -D -w $1 -h $1 $2 --export-png=$1x$1/$3 >/dev/null 2>&1
    fi
    if [ ! $? -eq 0 ]; then
        echo -n "ERROR "
    fi
}

function convert {
    # $1: source file
    echo -n "generating icons for $1... "
    NAME=`echo $1 | sed -e 's/svg$/png/'`

    if [[ $1 =~ Act.*\.svg ]]; then
        call_inkscape 16 $1 $NAME
    fi
    if [[ $1 =~ EditDetails\.svg ]]; then
        call_inkscape 16 $1 $NAME
    fi
    if [[ $1 =~ QMapShack\.svg ]]; then
        call_inkscape   8 $1 $NAME hicolor
        call_inkscape  16 $1 $NAME hicolor 
        call_inkscape  22 $1 $NAME hicolor 
        call_inkscape  24 $1 $NAME hicolor 
        call_inkscape  32 $1 $NAME hicolor 
        call_inkscape  36 $1 $NAME hicolor 
        call_inkscape  40 $1 $NAME hicolor 
        call_inkscape  42 $1 $NAME hicolor 
        call_inkscape  48 $1 $NAME hicolor 
        call_inkscape  64 $1 $NAME hicolor 
        call_inkscape  72 $1 $NAME hicolor 
        call_inkscape  80 $1 $NAME hicolor 
        call_inkscape  96 $1 $NAME hicolor 
        call_inkscape 128 $1 $NAME hicolor 
        call_inkscape 192 $1 $NAME hicolor 
        call_inkscape 256 $1 $NAME hicolor 
        call_inkscape 512 $1 $NAME hicolor
    fi

    call_inkscape 32 $1 $NAME
    call_inkscape 48 $1 $NAME

    echo ""
}

which inkscape >/dev/null 2>&1
if [ ! $? -eq 0 ]; then
    echo "this script requires inkscape, aborting..."
fi

if [ "$1" == "" ]; then
    echo "generating ALL icons..."
    for i in *.svg; do
        convert "$i"
    done
else
    if [ -f $1 ]; then
        convert "$1"
    else
        echo "$1 does not exist or is no regular file, aborting..."
    fi
fi

