#!/bin/bash

# require elogind or systemd
PIDFILE="${XDG_RUNTIME_DIR}/wall.pid"

declare -a PIDs

_wall() {
    xwinwrap -ov -s -st -sp -ni -nf -un -o 1.0 -g "$1" -- mpv --fullscreen\
        --no-stop-screensaver \
        --vo=gpu --hwdec=vaapi \
        --loop-file --no-audio --no-osc --no-osd-bar -wid WID --no-input-default-bindings \
        "$2" &
    PIDs+=($!)
}

while read p; do
    [[ $(ps -p "$p" -o comm=) == "xwinwrap" ]] && kill -9 "$p";
done < $PIDFILE

sleep 0.5

case $1 in
    --full) 
        for i in $(xrandr -q | grep " connected" | grep -oP '\d+x\d+\+\d+\+\d+')
        do
            _wall "$i" "$2"
        done;;
    --part)
        _wall 1920x1080+0+0 "$2"
        _wall 1920x1080+1920+0 "$3"
        ;;
    --random)
        dir="$HOME/Pictures/Animated"
        listing="$(/usr/bin/ls "$dir")"
        for i in $(xrandr -q | grep " connected" | grep -oP '\d+x\d+\+\d+\+\d+')
        do
            choice=$(echo "$listing" | shuf -n 1)
            _wall "$i" "$dir/$choice"
        done;;
    *) ;;
esac

printf "%s\n" "${PIDs[@]}" > $PIDFILE
