#!/usr/bin/env bash

# This script is copyrighted to Thomas Guymer and is licensed under the
# Creative Commons Attribution Non-Commercial 2.0 UK: England & Wales Licence.

# This script can be run in two ways:
# * type "bash script.sh" into a console window; or
# * type "./script.sh" into a console window.

# This script will:
#   * search for all the saved thumbnails on your KDE system; then
#   * check if the original file is present and delete the thumbnail if it is
#     not.

# Source run control ...
source "${BASH_ENV}" || exit 1

# Check that non-standard programs are installed. "standard" programs are
# anything that is specified in the POSIX.1-2008 standard (and the IEEE Std
# 1003.1 standard) or that is a BASH builtin command. Therefore, "non-standard"
# programs are anything that does not appear on the following two lists:
#   * https://pubs.opengroup.org/onlinepubs/9699919799/idx/utilities.html
#   * https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html
if ! type exiftool &> /dev/null; then
    echo "ERROR: \"exiftool\" is not installed." >&2
    exit 1
fi

# Define function ...
urldecode() {
    # NOTE: https://unix.stackexchange.com/a/187256
    local url_encoded="${1//+/ }"
    printf '%b' "${url_encoded//%/\\x}"
}

# Initialize counters and kernel type ...
kern=$(uname)
count=0                                                                         # [#]
total=0                                                                         # [B]

# Loop over directories (if present) ...
for dir in "${HOME}/.thumbnails"/*; do
    [[ ! -d "${dir}" ]] && continue

    echo "Removing surplus thumbnails from \"${dir}\" ..."

    # Loop over PNGs (if present) ...
    for png in "${dir}"/*.png; do
        [[ ! -f "${png}" ]] && continue

        # Extract URI tag (skip if not present) and extract URI from tag string
        # (skipping thumbnails for SFTP files) ...
        uri="$(exiftool -ThumbURI "${png}" 2> /dev/null)"
        [[ ${#uri} -eq 0 ]] && continue
        uri="${uri##* }"
        [[ ${uri:0:7} == "sftp://" ]] && continue

        # Decide how to handle the URI ...
        if [[ ${uri:0:7} == "file://" ]]; then
            # Decode the URI, trim the URI and skip if the original file still
            # exists ...
            uri="$(urldecode "${uri}")"
            uri="${uri:7}"
            [[ -f "${uri}" ]] && continue

            # Increment counters and remove thumbnail ...
            count=$((count + 1))                                                # [#]
            case $kern in
                Darwin)
                    total=$((total + $(stat -f %z "${png}")))                   # [B]
                    ;;
                FreeBSD)
                    total=$((total + $(stat -f %z "${png}")))                   # [B]
                    ;;
                Linux)
                    total=$((total + $(stat -c %s "${png}")))                   # [B]
                    ;;
                *)
                    echo "ERROR: Unknown kernel type." >&2
                    exit 1
            esac
            rm "${png}"
        else
            echo "ERROR: An unknown URI type has been found." >&2
            echo "       Thumbnail => ${png}" >&2
            echo "       URI       => ${uri}" >&2
            exit 1
        fi
    done
done

echo "Removed ${count} thumbnails which totaled $((total / 1024 / 1024)) MiB."
