#!/bin/bash
#mxfb_setwallpaper by Melber
#License: GPL-3.0+
export mxfb_setwallpaper_version=26.05.05

#export TEXTDOMAINDIR=/usr/share/locale
#export TEXTDOMAIN="xxx"
#source gettext.sh

#variables
export title="$(gettext 'MXFB Set Wallpaper')"
export class="mxfb-setwallpaper"
export iconpath="/usr/share/icons/hicolor/scalable/apps/mxfb-setwallpaper.svg"
export setwallpaper_confpath="$HOME/.config/MX-Linux/setwallpaper"
export setwallpaper_html="/tmp/wallpaper-list.html"

#first run check

if [ ! -f "$HOME/.fehbg" ]; then
    echo "#!/bin/sh
feh --no-fehbg --bg-scale '/usr/share/backgrounds/default25.png'" > "$HOME/.fehbg"
fi

mkdir -p "$setwallpaper_confpath"

if [ ! -f "$setwallpaper_confpath/setwallpaper.conf" ]; then
    echo "wallpaper_searchmode=recursive" > "$setwallpaper_confpath/setwallpaper.conf"
fi

if [ ! -f "$setwallpaper_confpath/directories" ]; then
    echo '/usr/share/backgrounds' > "$setwallpaper_confpath/directories"
fi


appsfile_check=$(grep mxfb-setwallpaper "$HOME/.fluxbox/apps" 2>/dev/null)

if [ -z "$appsfile_check" ]; then
    echo '[app] (class=mxfb-setwallpaper)
  [Dimensions]	{70% 70%}
  [Position]	(CENTER)	{0% 0%}
  [Close]	{yes}
[end]' >> "$HOME/.fluxbox/apps"
fi


#start

wallpaper_setup() {

fehbg_line=$(grep 'feh' "$HOME/.fehbg")
wallpaper_scale="${fehbg_line##* --bg-}"
wallpaper_scale="${wallpaper_scale%% *}"

wallpaper_old=()
IFS="'" read -ra _parts <<< "$fehbg_line"
for ((i=1; i<${#_parts[@]}; i+=2)); do
    wallpaper_old+=("${_parts[$i]}")
done

mapfile -t _screen_outputs < <(xrandr --query | awk '/ connected/{print $1}')
num_screens=${#_screen_outputs[@]}

if [ ! -f /tmp/wallpaper-settings ]; then
    echo "$wallpaper_scale All" > /tmp/wallpaper-settings
fi

if [ ! -f /tmp/wallpaper-dir ]; then
    mapfile -t wallpaper_getdir < "$setwallpaper_confpath/directories"
    export wallpaper_dir="${wallpaper_getdir[0]}"
else
    read -r wallpaper_dir < /tmp/wallpaper-dir
    export wallpaper_dir
fi


}


wallpaper_list() {

if [ "$wallpaper_dir" != "$wallpaper_dirold" ]; then

    wallpaper_dirold="$wallpaper_dir"

    source "$setwallpaper_confpath/setwallpaper.conf"

    depth_flag=()
    [ "$wallpaper_searchmode" = "notrecursive" ] && depth_flag=(-maxdepth 1)
    mapfile -t wallpaper_list < <(find "$wallpaper_dir" "${depth_flag[@]}" -type f \( -name '*.png' -o -name '*.jpg' \) | sort -f)

    theme_setting=$(gsettings get org.gnome.desktop.interface color-scheme)
    [ "$theme_setting" = "'prefer-dark'" ] && bg_color="#424242" || bg_color="#ececee"

cat << EOF > "$setwallpaper_html"
<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-color: $bg_color ;
  }
  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 150px));
    grid-auto-flow: dense;
    gap: 0px 20px;
    max-width: 1200px;
    margin: 20px auto;
  }

  .grid img {
    width: 100%;
    height: auto;
    cursor: pointer;
    border: 10px solid transparent;
    transition: border-color 0.3s;
  }

  .grid img:hover {
    border: 10px solid #c3d5f6;
    transition: border-color 0.3s;
  }

  .grid img.selected {
    border: solid 10px #0f56d9;
  }
</style>
</head>

<body>
<div class="grid">
EOF

    {
    for i in "${wallpaper_list[@]}"; do

    filename="${i##*/}"
    uri="file://$(realpath "$i")"
    hash=$(printf '%s' "$uri" | md5sum); hash="${hash%% *}"
    thumb_cache="$HOME/.cache/thumbnails/normal/$hash.png"

    if [ ! -f "$thumb_cache" ]; then
        convert "$i" -thumbnail 150x150 "$thumb_cache"
    fi

    i="${i// /|}"

    echo "<a href=\"$i\"> <img src=\"$thumb_cache\" title=\"$filename\"> </a>"

    done
    } >> "$setwallpaper_html"

    cat << EOF >> "$setwallpaper_html"
</div>

<script>
  const images = document.querySelectorAll('.grid img');

  images.forEach(img => {
    img.addEventListener('click', () => {
      images.forEach(i => i.classList.remove('selected'));
      img.classList.add('selected');
    });
  });
</script>

</body>
</html>

EOF

fi

}


wallpaper_chooser() {

#make wallpaper list

wallpaper_setup

wallpaper_list


#TRANSLATORS Button text
BTN_CLOSE="$(gettext 'Close')" ; BTN_CLOSE+='!window-close!'
#TRANSLATORS Button text
BTN_APPLY="$(gettext 'Set as wallpaper')" ; BTN_APPLY+='!gtk-ok!'
#TRANSLATORS Button text
BTN_ABOUT="$(gettext 'About')" ; BTN_ABOUT+='!help-about!'
#TRANSLATORS Button text
BTN_DIRECTORY="$(gettext 'Directory Settings')"; BTN_DIRECTORY+='!gtk-directory!'

key=$RANDOM

read -ra wallpaper_settings < /tmp/wallpaper-settings
wallpaper_scale="${wallpaper_settings[0]}"
wallpaper_screen="${wallpaper_settings[1]}"

scaling_list=(scale fill center tile)
settings_scale=$wallpaper_scale

for scale_listitem in "${scaling_list[@]}"; do
    [ "$scale_listitem" != "$wallpaper_scale" ] && settings_scale="$settings_scale!$scale_listitem"
done

screen_list=(All)
for ((i=0; i<num_screens; i++)); do
    screen_list+=("Screen$i")
done
[ "$num_screens" -gt 1 ] && screen_list+=(Span)
settings_screen=$wallpaper_screen

for screen_listitem in "${screen_list[@]}"; do
    [ "$screen_listitem" != "$wallpaper_screen" ] && settings_screen="$settings_screen!$screen_listitem"
done

{
yad --plug=$key --tabnum=1 \
--form --columns=4 --separator=" " \
--field="Scaling: ":CB "$settings_scale" \
--field="   Screen: ":CB "$settings_screen" \
> /tmp/wallpaper-settings &

stdbuf -eL -oL  yad --plug=$key --tabnum=2 \
--html --uri="$setwallpaper_html" --print-uri --disable-search --scroll \
> /tmp/wallpaper-output &

#TRANSLATORS Main window text 1
text_main1="$(gettext 'Current Directory')"

source "$setwallpaper_confpath/setwallpaper.conf"

if [ "$wallpaper_searchmode" = "recursive" ]; then
    #TRANSLATORS Main window text 2
    text_main2="$(gettext '(sub-directories included)')"
else
    #TRANSLATORS Main window text 2
    text_main2="$(gettext '(sub-directories excluded)')"
fi

yad --title="$title" --class="$class" --window-icon="$iconpath" \
--paned --key=$key --orient=vert --splitter=-40 \
--width=700 --height=500 --center \
--text="\n$text_main1: <b>$wallpaper_dir</b>\t$text_main2" --text-align=center \
--buttons-layout=spread \
--button="${BTN_ABOUT}":'bash -c "wallpaper_about"' \
--button="${BTN_DIRECTORY}":6 \
--button="${BTN_APPLY}":4 \
--button="${BTN_CLOSE}":2 \

ret=$?

} 2>/dev/null


case "$ret" in
    2 | 252 )
      alldone="yep"
    ;;

    4)
        wallpaper_selection="$(tail -1 /tmp/wallpaper-output)"
        
        if [ -z "$wallpaper_selection" ]; then
            #TRANSLATORS Main window text
            text_noselection="$(gettext 'You must select a wallpaper!')" 
            yad --title="$title" --class="mxfb-setwallpaper-warning" --window-icon="$iconpath" \
            --width=300 --height=100 --center --separator="" \
            --text="\n<b>$text_noselection\n</b>" --text-align=center \
            --button=yad-ok
    
        else
        
            wallpaper_selection="${wallpaper_selection#\'}"
            wallpaper_selection="${wallpaper_selection%\'}"
            wallpaper_selection="${wallpaper_selection#file://}"
            wallpaper_selection="${wallpaper_selection//|/ }"
            read -ra wallpaper_settings < /tmp/wallpaper-settings
            wallpaper_scale="${wallpaper_settings[0]}"
            wallpaper_screen="${wallpaper_settings[1]}"

            feh_output="feh --no-fehbg --bg-$wallpaper_scale"

            if [ "$wallpaper_screen" = "All" ]; then
                feh_output+=" '$wallpaper_selection'"
            elif [ "$wallpaper_screen" = "Span" ]; then
                feh_output="feh --no-fehbg --no-xinerama --bg-$wallpaper_scale '$wallpaper_selection'"
            else
                screen_num="${wallpaper_screen#Screen}"
                for ((i=0; i<num_screens; i++)); do
                    if [ "$i" -eq "$screen_num" ]; then
                        feh_output+=" '$wallpaper_selection'"
                    else
                        feh_output+=" '${wallpaper_old[$i]:-$wallpaper_selection}'"
                    fi
                done
            fi

            printf "#!/bin/sh\n%s\n" "$feh_output" > "$HOME/.fehbg"

            sh "$HOME/.fehbg"

            rm -f /tmp/wallpaper-output

        fi

    ;;

    6 )
      wallpaper_settings
    ;;

esac

}

# settings window
wallpaper_settings() {

unset settings_done

wallpaper_dirsettings() {

mapfile -t wallpaper_dirlist < "$setwallpaper_confpath/directories"


#TRANSLATORS Settings window text
text_settings1="$(gettext 'Select wallpaper directory')"

#TRANSLATORS Button text
BTN_REMOVE="$(gettext 'Remove from list')" ; BTN_REMOVE+='!list-remove!'
#TRANSLATORS Button text
BTN_ADD="$(gettext 'Add to list')" ; BTN_ADD+='!list-add!'
#TRANSLATORS Button text
BTN_SELECT="$(gettext 'Select')" ; BTN_SELECT+='!gtk-ok!'

source "$setwallpaper_confpath/setwallpaper.conf"

if [ "$wallpaper_searchmode" = "recursive" ]; then
    #TRANSLATORS Button text
    BTN_SEARCHMODE="$(gettext 'Exclude sub-directories')"
else
    #TRANSLATORS Button text
    BTN_SEARCHMODE="$(gettext 'Include sub-directories')"
fi


wallpaper_dir=$(yad --title="$title" --class="mxfb-setwallpaper-settings" --window-icon="$iconpath" \
--width=300 --height=300 --center --separator="" \
--text="<b>$text_settings1</b>\n" \
--list --column="Directory" --no-headers \
--button="${BTN_SEARCHMODE}":26 \
--button="${BTN_REMOVE}":24 \
--button="${BTN_ADD}":22 \
--button="${BTN_SELECT}":20  \
"${wallpaper_dirlist[@]}" \
)

case $? in

    20 )
        printf '%s\n' "$wallpaper_dir" > /tmp/wallpaper-dir

        {
            printf '%s\n' "$wallpaper_dir"
            for list_item in "${wallpaper_dirlist[@]}"; do
                [ "$list_item" != "$wallpaper_dir" ] && printf '%s\n' "$list_item"
            done
        } > "$setwallpaper_confpath/directories"

        settings_done=yes
    ;;

    22 )
        dir_new=$(yad --title="$title" --class="mxfb-setwallpaper-settings" --window-icon="$iconpath" \
        --width=300 --height=300 --center --separator="" \
        --text="Select directory" \
        --form --columns=1 \
        --field="":DIR "$HOME" \
        --button=yad-ok \
        )

        printf '%s\n' "$dir_new" >> "$setwallpaper_confpath/directories"
    ;;

    24 )
        grep -Fxv "$wallpaper_dir" "$setwallpaper_confpath/directories" > /tmp/wallpaper-dirs-tmp \
            && mv /tmp/wallpaper-dirs-tmp "$setwallpaper_confpath/directories"
    ;;

    26 )
        if [ "$wallpaper_searchmode" = "recursive" ]; then
            printf '%s\n' "wallpaper_searchmode=notrecursive" > "$setwallpaper_confpath/setwallpaper.conf"
        else
            printf '%s\n' "wallpaper_searchmode=recursive" > "$setwallpaper_confpath/setwallpaper.conf"
        fi

        unset wallpaper_dirold
    ;;

    252 )
        settings_done=yes
    ;;

esac

}

until [ "$settings_done" = "yes" ]; do
    wallpaper_dirsettings
done


}

# about window
wallpaper_about() {

#TRANSLATORS Text in About window
text_about=$(gettext "MX-Fluxbox wallpaper chooser.")

iconpath96="/usr/share/icons/hicolor/scalable/apps/mxfb-setwallpaper96.svg"

yad --about --class="mxfb-setwallpaper-about" --window-icon="$iconpath" \
--width=600 --height=500 --center \
--image="$iconpath96" \
--pname="$title" \
--pversion="$mxfb_setwallpaper_version" \
--comments="$text_about" \
--website-label="https://mxlinux.org/" \
--website="https://mxlinux.org/" \
--copyright="Copyright (c) 2026 Melber" \
--authors="Melber,MX Devs" \
--license="GPL3" 

}


export -f wallpaper_setup wallpaper_list wallpaper_chooser wallpaper_about wallpaper_settings


until [ "$alldone" = "yep" ]; do
    wallpaper_chooser
done

rm -f /tmp/wallpaper-output /tmp/wallpaper-settings /tmp/wallpaper-dir "$setwallpaper_html"

exit
