#!/usr/bin/env bash
set -euo pipefail

marker_dir="${HOME}/.config/raveos"
marker_file="${marker_dir}/plasma-first-login-done"
wallpaper="/usr/share/backgrounds/raveos/raveos-main-bg.jpeg"
kickoff_image="/usr/share/raveos/plasma-theme/theme-data/plasma/org.kde.plasma.kickoff.svg"

mkdir -p "${marker_dir}"
[[ -e "${marker_file}" ]] && exit 0
[[ "${XDG_CURRENT_DESKTOP:-}" == *KDE* || "${DESKTOP_SESSION:-}" == *plasma* ]] || exit 0

until qdbus6 org.kde.plasmashell /PlasmaShell >/dev/null 2>&1 || qdbus org.kde.plasmashell /PlasmaShell >/dev/null 2>&1; do
    sleep 2
done

sleep 5

QDBUS=""
if command -v qdbus6 >/dev/null 2>&1; then
    QDBUS="qdbus6"
elif command -v qdbus >/dev/null 2>&1; then
    QDBUS="qdbus"
fi

if command -v plasma-apply-lookandfeel >/dev/null 2>&1; then
    plasma-apply-lookandfeel -a org.kde.breezedark.desktop >/dev/null 2>&1 || true
fi

if [[ -f "${wallpaper}" ]] && command -v plasma-apply-wallpaperimage >/dev/null 2>&1; then
    plasma-apply-wallpaperimage "${wallpaper}" >/dev/null 2>&1 || true
fi

if [[ -n "$QDBUS" ]]; then
    $QDBUS org.kde.plasmashell /PlasmaShell org.kde.PlasmaShell.evaluateScript "
        if ('${wallpaper}' !== '') {
            var d = desktops();
            for (var i = 0; i < d.length; i++) {
                d[i].wallpaperPlugin = 'org.kde.image';
                d[i].currentConfigGroup = ['Wallpaper', 'org.kde.image', 'General'];
                d[i].writeConfig('Image', 'file://${wallpaper}');
                d[i].writeConfig('FillMode', 2);
            }
        }
        if ('${kickoff_image}' !== '') {
            function setKickoff(applet, path) {
                var g = [['Configuration', 'General'], ['General']];
                for (var i = 0; i < g.length; i++) {
                    applet.currentConfigGroup = g[i];
                    applet.writeConfig('useCustomButtonImage', 'true');
                    applet.writeConfig('customButtonImage', 'file://' + path);
                    applet.writeConfig('icon', path);
                }
            }
            var p = panels();
            for (var i = 0; i < p.length; i++) {
                var a = p[i].applets;
                for (var j = 0; j < a.length; j++) {
                    var pl = a[j].pluginName;
                    if (pl === 'org.kde.plasma.kickoff' || pl === 'org.kde.plasma.kicker' || pl === 'org.kde.plasma.simplemenu' || pl === 'org.kde.plasma.kickoffdashboard') {
                        setKickoff(a[j], '${kickoff_image}');
                    }
                }
            }
        }
    " >/dev/null 2>&1 || true
fi

touch "${marker_file}"
