#!/bin/sh

# Written by:      fennek182
# Version:         4
# Last change:     Sun 2026-06-14
# Git repo:        https://git.fennek.xyz/fennek182/dotfiles
# Latest version:  https://git.fennek.xyz/fennek182/dotfiles/src/branch/main/.local/bin/stats
# Description:     This is a script for managing the wallpaper/background image

# TODO: add comments to better describe functionality

pick_random_wallpaper () {
    image=$(/bin/ls "$HOME/pix/wallpaper/desktop" | grep -E '(jpg|jpeg|png)$' | sort -R | tail -1)
    path="$HOME/pix/wallpaper/desktop/$image"
}

run_cmd () {
	cmd_string="hyprctl 'dispatch hl.dsp.exec_cmd(\"$@\")'"
	echo $cmd_string
	eval $cmd_string
}

set_bg () {
    echo "setting bg..."
    swaybg_pid=$(pidof swaybg)
    run_cmd "swaybg -i $(tail -n1 /tmp/wallpaper)" > /dev/null 2>&1
    sleep 0.5
    kill $swaybg_pid
    sleep 2 && copy_wallpaper
}

copy_wallpaper() {
    echo "running copy proccess..."
    /bin/cp -f "$(tail -n1 /tmp/wallpaper)" ~/.config/wallpaper
    /bin/cp -f "/tmp/wallpaper" "/tmp/wallpaper_set"
}

case $1 in
    "--restore")
      # restores previously set wallpaper (e.g. on startup):
        echo "~/.config/wallpaper" > /tmp/wallpaper
        echo "~/.config/wallpaper" > /tmp/wallpaper_set
        set_bg
    ;;

    "--copy")
      copy_wallpaper
    ;;

    "--file")
        echo $2 > /tmp/wallpaper
        set_bg
    ;;

    "--pick")
      # deprecated - wip, searching for new UIs to pick a wallpaper
    ;;

  * | "--random")
      # when no parameter is given, pick a random image from wallpaper folder
      # choose random wallpaper again if current wallaper is the same
      # overwrite symlink to ~/.config/wallpaper
      pick_random_wallpaper
      # while [ $(tail -n1 /tmp/wallpaper) -ef "$path" ]; do pick_random_wallpaper; done
      echo $path > /tmp/wallpaper
      echo "setting wallpaper $path"
      set_bg
    ;;
esac
