#!/bin/bash
#mxfb_setwallpaper by Melber
#License: GPL-3.0+
mxfb_wallpaper_version=26.05.03

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

#first run check

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

appsfile_check=$(grep "mxfb-setwallpaper" $HOME/.fluxbox/apps)

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

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

#first run check

appsfile_check=$(grep mxfb-setwallpaper $HOME/.fluxbox/apps)

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

if [ ! -f "$HOME/.config/MX-Linux/setwallpaper/directories" ]; then
    mkdir -p "$HOME/.config/MX-Linux/setwallpaper"
    echo '/usr/share/backgrounds' > "$HOME/.config/MX-Linux/setwallpaper/directories"
fi

#start

wallpaper_setup() {

wallpaper_scale="${wallpaper_current[2]}"
wallpaper_scale=$(grep 'feh' $HOME/.fehbg | cut -d " " -f 3)
wallpaper_scale="$(echo $wallpaper_scale | sed -e 's/--bg-//' )"
    
wallpaper_old1=$(grep 'feh' $HOME/.fehbg | cut -d "'" -f 2)
wallpaper_old2=$(grep 'feh' $HOME/.fehbg | cut -d "'" -f 4)
    
if [ -z "$wallpaper_old2" ]; then
    wallpaper_old2="$wallpaper_old1"
fi

if [ -z "$wallpaper_dir" ]; then
    wallpaper_dir=/usr/share/backgrounds
fi

echo "$wallpaper_scale Screen0" > /tmp/wallpaper-settings


if [ ! -f /tmp/wallpaper-dir ]; then
    if [ ! -f $HOME/.config/MX-Linux/setwallpaper/directories ]; then
        echo "/usr/share/backgrounds" > $HOME/.config/MX-Linux/setwallpaper/directories
    fi
    mapfile -t wallpaper_getdir < "$HOME/.config/MX-Linux/setwallpaper/directories"
    export wallpaper_dir="${wallpaper_getdir[0]}"
else
    export wallpaper_dir="$(cat /tmp/wallpaper-dir)"
fi


}


wallpaper_list() {

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

    wallpaper_dirold="$wallpaper_dir"
    
    old_ifs="$IFS"
    IFS="
"

    wallpaper_list=$(find "$wallpaper_dir" -type f \( -name '*.png' -o -name '*.jpg' \) | sort -f)

#convert list to array
    wallpaper_list=($wallpaper_list)

    theme_setting=$(gsettings get org.gnome.desktop.interface color-scheme)

    if [ "$theme_setting" = "'prefer-dark'" ]; then

cat << EOF > $wallpaper_html
<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-color: #424242 ;
  }
EOF

    else

    cat << EOF > $wallpaper_html
<!DOCTYPE html>
<html>
<head>
<style>
  body {
    background-color: #ececee ;
  }
EOF

    fi

cat << EOF >> $wallpaper_html
  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    grid-auto-flow: dense;
    gap: 0px 20px;
    max-width: 900px;
    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
#here new#

    filename=$(basename "$i")
    uri="file://$(realpath "$i")"
    hash=$(echo -n "$uri" | md5sum | cut -d' ' -f1)
    thumb_cache=$(find ~/.cache/thumbnails/normal -name "$hash.png" 2>/dev/null)

    if [ -z "$thumb_cache" ]; then
    
        if [ ! -d /tmp/wallthumbs/ ]; then
        mkdir /tmp/wallthumbs/
        fi

        convert "$i" -thumbnail 150x150 "$HOME/.cache/thumbnails/normal/$hash"
        thumb_cache="$HOME/.cache/thumbnails/normal/$hash"

    fi
    
    i=$(echo "$i" | sed -e 's/ /|/g')
    filename=$(echo "$filename" | sed -e "s/ /\&nbsp\;/g")
    
    echo "<a href="$i"> <img src="$thumb_cache" title="$filename"> </a>" >> $wallpaper_html

    
    done

    cat << EOF >> $wallpaper_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

    IFS="$old_ifs"

fi

}


wallpaper_chooser() {

#make wallpaper list

wallpaper_setup

wallpaper_list


#TRANSLATORS Main window text
wallpaper_text1="$(gettext 'Select wallpaper')" 
#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_SETTINGS="$(gettext 'Settings')"; BTN_SETTINGS+='!settings!'
#TRANSLATORS Button text
BTN_DIRECTORY="$(gettext 'Change Directory')"; BTN_DIRECTORY+='!gtk-directory!'


key=$RANDOM

if [ "$wallpaper_scale" = "scale" ]; then
    settings_scale='scale!fill!center'
elif [ "$wallpaper_scale" = "fill" ]; then
    settings_scale='fill!scale!center'
elif [ "$wallpaper_scale" = "center" ]; then
    settings_scale='center!fill!scale'
fi


if [ "$wallpaper_screen" = "Screen0" ]; then
    settings_screen='Screen0!Screen1!All!Span'
elif [ "$wallpaper_screen" = "Screen1" ]; then
    settings_screen='Screen1!Screen0!All!Span'
elif [ "$wallpaper_screen" = "Span" ]; then
    settings_screen='Span!All!Screen0!Screen1'
else
    settings_screen='All!Screen0!Screen1!Span'
fi



{
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="$wallpaper_html" --print-uri --disable-search --scroll \
> /tmp/wallpaper-output &

text_main1="$(gettext 'Current Directory')"

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>" --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=$(echo "$wallpaper_selection" | sed -e "s|\'/||g" | sed -e 's|file://||' )
            wallpaper_selection=$(echo "$wallpaper_selection" | sed -e 's/|/ /g')
            wallpaper_settings=$(cat /tmp/wallpaper-settings)
            wallpaper_settings=($wallpaper_settings)
            wallpaper_scale="${wallpaper_settings[0]}"
            wallpaper_screen="${wallpaper_settings[1]}"
            xinerama_selection=''
        
            if [ "$wallpaper_screen" = "All" ]; then
                xinerama_selection=''
                wallpaper_1=''
                wallpaper_2=''
        
            elif [ "$wallpaper_screen" = "Screen0" ]; then
                xinerama_selection=''
                wallpaper_1=''
                wallpaper_2="$wallpaper_old2"

            elif [ "$wallpaper_screen" = "Screen1" ]; then
                xinerama_selection=''
                wallpaper_1="$wallpaper_old1"
                wallpaper_2=''
                                   
            elif [ "$wallpaper_screen" = "Span" ]; then
                xinerama_selection='--no-xinerama'
                wallpaper_1=''
                wallpaper_2=''
            fi

            feh_output="feh --no-fehbg --bg-wallpaper_scale xinerama_selection 'wallpaper_1' 'wallpaper_selection' 'wallpaper_2'"
            

            
            feh_output=$(echo "$feh_output" | sed -e "s/--bg-wallpaper_scale/--bg-$wallpaper_scale/")
            feh_output=$(echo "$feh_output" | sed -e "s/xinerama_selection/$xinerama_selection/")
            feh_output=$(echo "$feh_output" | sed -e "s|wallpaper_1|$wallpaper_1|")
            feh_output=$(echo "$feh_output" | sed -e "s|wallpaper_selection|$wallpaper_selection|")
            feh_output=$(echo "$feh_output" | sed -e "s|wallpaper_2|$wallpaper_2|")
            feh_output=$(echo "$feh_output" | sed -e 's/   / /g')
            feh_output=$(echo "$feh_output" | sed -e 's/  / /g')
            feh_output=$(echo "$feh_output" | sed -e "s/''//g")
            
            echo "#!/bin/sh
$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 < "$HOME/.config/MX-Linux/setwallpaper/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!'


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_REMOVE}":24 \
--button="${BTN_ADD}":22 \
--button="${BTN_SELECT}":20  \
"${wallpaper_dirlist[@]}" \
)

case $? in

    20 )
        echo "$wallpaper_dir" > /tmp/wallpaper-dir

        echo "$wallpaper_dir" > "$HOME/.config/MX-Linux/setwallpaper/directories"
        for list_item in "${wallpaper_dirlist[@]}"; do
            if [ "$list_item" != "$wallpaper_dir" ]; then
            echo "$list_item" >> "$HOME/.config/MX-Linux/setwallpaper/directories"
            fi
        done

        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 \
        )

        echo "$dir_new" >> $HOME/.config/MX-Linux/setwallpaper/directories
    ;;

    24 )
        sed -i "\|^$wallpaper_dir$|d" $HOME/.config/MX-Linux/setwallpaper/directories
    ;;

    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_wallpaper_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 $wallpaper_html

exit
