#!/bin/bash

# Path to the image is the first argument
IMAGE="$1"
image_name=$(basename "$IMAGE")
image="$HOME/Pictures/Wallpapers/$image_name"

echo "start"

# Check if an image was provided
if [[ -z "$IMAGE" ]]; then
    echo "Usage: $0 /path/to/image"
    exit 1
fi


if [ -x "/usr/bin/swww-daemon" ]; then
    echo "swww-daemon exists and is executable"

    # Check if swww daemon is running
    if ! pgrep -x "swww-daemon" > /dev/null; then
        echo "Starting swww daemon..."
        swww-daemon &

        # Give the daemon a moment to start
        sleep 0.2
        echo "daemon started"
    fi

    # Set the wallpaper
    echo "running"
    swww img "$image" -t grow --transition-duration 1

elif [ -x "/usr/bin/hyprpaper" ]; then
    echo "hyprpaper exists and is executable"

    if ! pgrep -x "hyprpaper" > /dev/null; then
        echo "Starting hyprpaper daemon..."
        hyprpaper &

        # Give the daemon a moment to start
        sleep 0.2
        echo "daemon started"
    fi
    sed -i "3s|path = .*|path = ${image}|" ~/.config/hypr/hyprpaper.conf

    hyprctl monitors -j | jq -r 'sort_by(.id) | .[].name' | while IFS= read -r display; do
        hyprctl hyprpaper wallpaper "$display, $image"
    done
fi

if [ -x "/usr/bin/matugen" ]; then
    matugen image $image --mode dark --source-color-index 0
else
    cp $HOME/.config/quickshell/colors/example_colors.qml $HOME/.config/quickshell/colors/Colors.qml
fi

### Blured Wallpaper for wlogout
blur="50x30"
static_wallpaper_dir="$HOME/Pictures/Wallpapers/Static"

if [ ! -d $static_wallpaper_dir ]; then
  mkdir -p $static_wallpaper_dir;
fi

current_wallpaper="$static_wallpaper_dir/current"

echo "$image" > $current_wallpaper

blurred_wp="$static_wallpaper_dir/blurred.jpg"

if [ -x "/usr/bin/sddm" ]; then
    magick $image -blur $blur $blurred_wp
else
    cp $image $blurred_wp
fi
if [ -x "/usr/bin/sddm" ] && [ -d "/usr/share/backgrounds" ]; then
    sddm_background="/usr/share/backgrounds/background.jpg"
    cp "$image" "$sddm_background"
fi

echo "test"
