#!/bin/bash

# Only wrap the original binary once. We detect this by checking that
# /usr/lib/kscreenlocker_greet is still an ELF executable.
if [ -x /usr/lib/kscreenlocker_greet ] && file --mime-type /usr/lib/kscreenlocker_greet | grep -Eq 'application/x-(pie-)?executable'; then

    # Keep a backup of the original binary so the wrapper can delegate to it.
    mv -f /usr/lib/kscreenlocker_greet /usr/lib/kscreenlocker_greet_orig

    # Install a small wrapper script. The single-quoted heredoc prevents
    # accidental variable expansion while generating the file.
    cat <<'EOF' > /usr/lib/kscreenlocker_greet
#!/bin/sh

# Check if the process 'kwin_wayland' is running
if pgrep -f 'bin/kwin_wayland' >/dev/null 2>&1; then
    # If running under Wayland, send a SIGHUP signal to the original kscreenlocker_greet
    killall -1 kscreenlocker_greet_orig
    # Invoke the original binary to lock the screen immediately, sleep for 1 second, and re-lock
    /usr/lib/kscreenlocker_greet_orig --immediateLock
    sleep 1
    /usr/lib/kscreenlocker_greet_orig --immediateLock
else
    # If not under Wayland, call the original binary with any passed arguments
    /usr/lib/kscreenlocker_greet_orig "$@"
fi
EOF
    chmod +x /usr/lib/kscreenlocker_greet
fi

# Exit the script with a success code
exit 0
