#!/bin/bash
####################################################################
#                                                                  #
#  Checks an XML theme file for all links to PNG files and         #
#  runs through folder to see if all files are present!            #
#  Also shows a list of PNG files not in use anymore.              #
#                                                                  #
#  Scripted by Koentje  (remon@cobrasoft.nl)                       #
#                                                    version 1.0   #
####################################################################

if [ "$1" = "" ]; then
  echo -e "\n Checks in XML if links to png files are present in folder!"
  echo -e "\n  Usage: $(basename $0) <xmlfile>\n"
  exit
fi

tabs 50
srcpath=$(readlink -f $1)
workdir=$(dirname $srcpath)
echo -e "\nPNG folder: $workdir\n"

cd "$workdir"
filelist=$(ls -1 *.png)
cd $PWD


# Check XML file for PNG links to PNG files present in folder
while read -r xml
do

    x=0
    while read -r png
    do
        if [ "$xml" = "$png" ]; then
          x=$((x+1))
        fi
    done< <(echo "$filelist")

    if [ "$x" = "0" ]; then
      echo -e "[XML] $xml\t \e[31m[ MISSING ]\e[m"
    elif [ "$x" -gt "0" ]; then
      echo -e "[XML] $xml\t \e[32m[ PRESENT ]\e[m"
    fi

done< <(cat "$1" | grep '.png' | awk -F'filename=\"' '{print $2}' | awk -F'\"' '{print $1}')
unset xml png x



# Checks PNG files in folder not in use anymore by XML file
echo -e "\n\nPNG files in folder no longer used by XML:\n"
while read -r png
do

    x=0
    while read -r xml
    do
          if [ "$png" = "$xml" ]; then
            x=$((x+1))
          fi

    done< <(cat "$1" | grep '.png' | awk -F'filename=\"' '{print $2}' | awk -F'\"' '{print $1}')

    if [ "$x" = "0" ]; then
      echo -e "[PNG] $png\t \e[31m[ NOT USED ]\e[m"
#    elif [ "$x" -gt "0" ]; then
#      echo -e "[PNG] $png\t \e[32m[ IN USE ]\e[m"
    fi

done< <(echo "$filelist")
echo
