#!/bin/bash

# Empty Folder Cleaner

ICON="/usr/share/icons/hicolor/48x48/apps/empty-folder-cleaner.png"
OK="/usr/share/empty-folder-cleaner/icons/ok.svg"
CANCEL="/usr/share/empty-folder-cleaner/icons/cancel.svg"
APPNAME="Empty Folder Cleaner"
FOLDER="/usr/share/empty-folder-cleaner/icons/folder.svg"

# Initial Warning Dialog
yad --height=100 --width=400 --center --fixed \
    --title="$APPNAME" --image="$ICON" \
    --window-icon="$ICON" \
    --text="\nUse caution when removing empty directories!" \
    --button="Cancel!$CANCEL":1 \
    --button="Ok!$OK":0

if [ $? -ne 0 ]; then
    exit 0
fi

# Select path to scan
SCAN_PATH=$(yad --window-icon="$ICON" --center --fixed \
    --title="$APPNAME" \
    --file --file-selection --filename="/home/$USER" \
    --directory \
    --width=700 \
    --height=500)

[[ $? -ne 0 ]] && exit 0

# Find empty directories (deepest first)
mapfile -t DIRS < <(
    find "$SCAN_PATH" \
    \( -path "/dev" -o -path "/proc" -o -path "/run" -o -path "/var" -o -path "/home" -o -path "/root" \) -prune \
    -o -depth -type d -empty -print 2>/dev/null | sort
)



COUNT=${#DIRS[@]}

if [[ $COUNT -eq 0 ]]; then
    yad --info --height=100 --width=375 --center --fixed \
        --title="$APPNAME" --image="$ICON" --window-icon="$ICON" \
        --text="\nNo empty directories found." \
        --button="Ok!$OK":1
    exit 0
fi

# checklist
LIST=()
for dir in "${DIRS[@]}"; do
    LIST+=(FALSE "$dir")
done

# We use newline '\n' as a separator to completely avoid delimiter issues
SELECTED=$(yad \
    --title="$APPNAME" \
    --width=700 \
    --height=500 --window-icon="$ICON" \
    --list \
    --checklist \
    --separator="\n" \
    --column="Delete" \
    --column="Empty Directory" \
    "${LIST[@]}")

[[ $? -ne 0 ]] && exit 0

if [[ -z "$SELECTED" ]]; then
    yad --info --height=100 --width=375 --center --fixed \
        --title="$APPNAME" --image="$ICON" --window-icon="$ICON" \
        --text="\nNo empty directories selected." \
        --button="Ok!$OK:1"
    exit 0
fi

# Convert the newline-separated string directly into a clean Bash array
mapfile -t CHOSEN <<< "$SELECTED"
NUM_SELECTED=${#CHOSEN[@]}

yad --height=100 --width=425 --center --fixed \
    --title="$APPNAME" --image="$ICON" --window-icon="$ICON" \
    --text="\nAre you sure you want to delete these director$( [[ $NUM_SELECTED -eq 1 ]] && echo 'y' || echo 'ies' )?" \
    --button="No!$CANCEL":1 \
    --button="Yes!$OK":0
[[ $? -ne 0 ]] && exit 0

REMOVED=0
FAILED=0

for dir in "${CHOSEN[@]}"; do
    # Skip any accidental empty lines just in case
    [[ -z "$dir" ]] && continue

    if rmdir "$dir" 2>/dev/null; then
        ((REMOVED++))
    else
        ((FAILED++))
    fi
done

# Final completion message with actual stats
yad --info --height=100 --width=400 --center --fixed \
    --title="$APPNAME" --image="$ICON" \
    --window-icon="$ICON" \
    --text="\nSuccessfully removed $REMOVED directories." \
    --button="Ok!$OK":1
