#!/bin/bash
# Special for Ximper Linux

if [[ $# -ne 1 ]]; then
  echo "Usage: ./imagetognomexml path_to_image_folder"
  exit 1
fi

image_folder="$1"

if [[ ! -d "$image_folder" ]]; then
  echo "Error: Image folder '$image_folder' does not exist."
  exit 2
fi

# Check if the path contains "/usr/src/tmp/branding-etersoft-ximper-buildroot"
if [[ "$image_folder" == *"/usr/src/tmp/branding-etersoft-ximper-buildroot"* ]]; then
  # Get the relative path without '/usr/src/tmp/branding-etersoft-ximper-buildroot'
  relative_path=/$(realpath --relative-to="/usr/src/tmp/branding-etersoft-ximper-buildroot" "$image_folder")
else
  relative_path="$image_folder"
fi

xml_file="$image_folder$(basename "$image_folder").xml"

echo '<?xml version="1.0" encoding="UTF-8"?>' > "$xml_file"
echo '<!DOCTYPE wallpapers SYSTEM "gnome-wp-list.dtd">' >> "$xml_file"
echo '<wallpapers>' >> "$xml_file"

for image_file in "$image_folder"/*; do
  if [[ -f "$image_file" ]]; then
    image_name=$(basename "$image_file")
    image_name_no_ext="${image_name%.*}"
    xml_escaped_name=$(echo "$image_name_no_ext" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'\''/\&apos;/g')
    xml_escaped_name_de=$(echo "$xml_escaped_name" | sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g; s/'\''/\&apos;/g')
    xml_filename="$relative_path/$(basename "$image_file")"

    echo '  <wallpaper deleted="false">' >> "$xml_file"
    echo "    <name>$xml_escaped_name</name>" >> "$xml_file"
    echo "    <name xml:lang=\"de\">$xml_escaped_name_de</name>" >> "$xml_file"
    echo "    <filename>$xml_filename</filename>" >> "$xml_file"
    echo '    <options>zoom</options>' >> "$xml_file"
    echo '    <shade_type>solid</shade_type>' >> "$xml_file"
    echo '    <pcolor>#ffffff</pcolor>' >> "$xml_file"
    echo '    <scolor>#000000</scolor>' >> "$xml_file"
    echo '  </wallpaper>' >> "$xml_file"
  fi
done

echo '</wallpapers>' >> "$xml_file"

echo "XML file '$xml_file' has been created in the $image_folder directory."

exit 0