#!/bin/bash
# Diskspace, show sizes of files in a selected folder.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

# Target the folder from right-click or current PWD
TARGET="${1:-$PWD}"
if [[ -d "$TARGET" ]]; then
    cd "$TARGET"
else
    cd "$(dirname "$TARGET")"
fi

# Function to feed YAD with Size | Short Name | Absolute Path
get_files() {
    find . -mindepth 1 -maxdepth 1 | xargs -d '\n' du -sh 2>/dev/null | sort -rh | perl -ne '
        if (m/^(\S+)\s+\.\/(.*)$/) {
            my ($s, $p) = ($1, $2);
            my $abs = qx(readlink -f "$p");
            chomp($abs);
            print "$s\n$p\n$abs\n";
        }'
}

export -f get_files

while true; do
    # --print-column=3 ensures we only get the full path back from YAD
    CHOICE=$(get_files | yad \
        --list \
        --column="Size" \
        --column="File/Folder Name" \
        --column="Full Path":HD \
        --title="AVL-MXe Action - Show Large Files" \
        --text="<b>Browsing:</b> $PWD\nDouble-click to Open | Select and click Delete" \
        --width=750 \
        --height=500 \
        --image=/usr/local/share/icons/custom/diskspace-app.png \
        --window-icon=/usr/local/share/icons/custom/diskspace.png \
        --center \
        --borders=24 \
        --print-column=3 \
        --button="Delete":10 \
        --button="Exit":1)

    EXIT_STATUS=$?

    # Exit/Escape/Close
    [[ $EXIT_STATUS -eq 1 || $EXIT_STATUS -eq 252 ]] && break

    # Double-click detected
    if [[ $EXIT_STATUS -eq 0 ]]; then
        # YAD adds a trailing pipe, so we strip it
        FILE_TO_OPEN=$(echo "$CHOICE" | cut -d'|' -f1)
        if [[ -n "$FILE_TO_OPEN" ]]; then
            thunar "$FILE_TO_OPEN" &
        fi
        break
    fi

    # Delete (Trash) detected
    if [[ $EXIT_STATUS -eq 10 ]]; then
        FILE_TO_DELETE=$(echo "$CHOICE" | cut -d'|' -f1)
        
        if [[ -n "$FILE_TO_DELETE" ]]; then
            yad --question --text="Are you sure you want to trash:\n\n<b>$FILE_TO_DELETE</b>?" \
                --button="Cancel":1 --button="Move to Trash":0 --center --width=500 \
                --title="Confirm Trash" --window-icon=user-trash

            if [[ $? -eq 0 ]]; then
                gio trash "$FILE_TO_DELETE"
            fi
        fi
    fi
done