#!/bin/bash
#
# EndeavourOS initial wallpaper installer for a user.
#

#################################################################################
EOS_SCRIPTS_YAD=/usr/share/endeavouros/scripts/eos-script-lib-yad
source $EOS_SCRIPTS_YAD || {
    echo "ERROR: cannot find $EOS_SCRIPTS_YAD" >&2
    exit 1
}
unset EOS_SCRIPTS_YAD

export -f eos_yad
export -f eos_yad_terminal
export -f eos_yad_check_internet_connection
export -f eos_yad_GetArgVal
export -f eos_yad_RunCmdTermBash
export -f eos_yad_problem
export -f eos_yad_DIE
export -f eos_yad_WARN
export -f eos_yad__detectDE
export -f eos_yad_GetDesktopName
#################################################################################


Main() {
    test -x /usr/bin/calamares && return   # don't change wallpaper while installing system

    local EOS_version=$(cat /usr/lib/endeavouros-release | cut -d'=' -f2 | cut -d' ' -f1)
    [ $(vercmp "$EOS_version" "2022.11.15") -ge 0  ] && return  # wallpaper already set by calamares

    local DE="$(eos_GetDeOrWm)"
    local conf="$HOME/.config/EOS-initial-wallpaper.$DE"

    case "$DE" in
        SWAY | BSPWM | QTILE | OPENBOX)
            return ;;      # don't change wallpaper on community editions
        XFCE)
            local pkg=endeavouros-skel-xfce4
            local ver=$(pacman -Q $pkg 2>/dev/null | awk '{print $2}')

            if [ $(vercmp "$ver" "2.17-1") -gt 0 ] ; then
                return            # new $pkg will handle the wallpaper
            fi
            ;;
    esac

    case "$1" in
        -r)  /usr/bin/rm -f "$conf" ;;            # -r re-installs the default wallpaper now
        -rr) /usr/bin/rm -f "$conf" ; return ;;   # same as -r, but not now
    esac

    # Set default wallpaper only if no DE specific config file is found.
    [ -r "$conf" ] && return

    sleep 3
    eos-wallpaper-set DEFAULT-2021
    touch "$conf"
}

Main "$@"
