#!/usr/bin/env bash

# Check requirements
wai=$(dirname $(readlink -f "$0")) # Current script directory
[ $(command -v "convert") ] ||  { echo -e "\e[31mThis script require ImageMagick installed.\e[0m"; exit 1; }
[ $(command -v "inkscape") ] ||  { echo -e "\e[31mThis script require Inkscape installed.\e[0m"; exit 1; }
[ -d "${wai}/../../assets/" ] || { echo -e "\e[31mUnable to found assets folder.\e[0m"; exit 1; }
boards_path="${wai}/../../assets/boards/" && mkdir -p ${boards_path}
pieces_path="${wai}/../../assets/pieces/" && mkdir -p ${pieces_path}

generate () {
    echo -e "\e[32mGenerating skin $(basename $1)\e[0m"
    
    # Configure black's pieces
    bk=$1/bk.png
    bq=$1/bq.png
    br=$1/br.png
    bb=$1/bb.png
    bn=$1/bn.png
    bp=$1/bp.png
    bs=$1/bs.png
    # Configure white's pieces
    wk=$1/wk.png
    wq=$1/wq.png
    wr=$1/wr.png
    wb=$1/wb.png
    wn=$1/wn.png
    wp=$1/wp.png
    ws=$1/ws.png

    # First build the png files
    for svg in $(find "$1/" -name "*.svg")
    do
        outFile=$(basename $svg|sed "s/\.svg$//g").png
        inkscape -z -e $1/$outFile -w 200 -h 200 $svg > /dev/null
    done
    
    if [ ! -e "$ws" ] # Generate Pieces Skin
    then
        convert \( $bk $wk +append \) \
                \( $bq $wq +append \) \
                \( $br $wr +append \) \
                \( $bb $wb +append \) \
                \( $bn $wn +append \) \
                \( $bp $wp +append \) \
                -background none -append  "${pieces_path}/$(basename "$1").png"
    else # Generate Squares Skin
        convert \( $bs $ws +append \) \
                -background none -append  "${boards_path}/$(basename "$1").png"
    fi

    rm $1/*.png
}


if [ $# -eq 1 ]
then
    # Generate assets for each skin
    for skin in $({ ls -d ${wai}/boards/*; ls -d ${wai}/pieces/*; } | grep "$1")
    do
        generate $skin
    done
else
    # Generate assets for each skin
    for skin in $({ ls -d ${wai}/boards/*; ls -d ${wai}/pieces/*; })
    do
        generate $skin
    done
fi
