#!/usr/bin/env bash

# ==================================================
# CAMBIO AUTOMÁTICO DE FONDO DE PANTALLA
# ==================================================

WALLPAPER_DIR="$HOME/.config/backgrounds"
OUTPUT="DP-4"
INTERVAL=600

# Buscar imágenes disponibles
mapfile -d '' WALLPAPERS < <(
    find "$WALLPAPER_DIR" -type f \
        \( -iname '*.jpg' \
        -o -iname '*.jpeg' \
        -o -iname '*.png' \
        -o -iname '*.webp' \
        -o -iname '*.bmp' \) \
        -print0
)

# Comprobar que existen imágenes
if [ "${#WALLPAPERS[@]}" -eq 0 ]; then
    echo "No se han encontrado imágenes en $WALLPAPER_DIR"
    exit 1
fi

CURRENT_PID=""

# Limpiar al cerrar el script
cleanup() {
    if [ -n "$CURRENT_PID" ]; then
        kill "$CURRENT_PID" 2>/dev/null || true
        wait "$CURRENT_PID" 2>/dev/null || true
    fi
}

trap cleanup EXIT INT TERM

# Bucle principal
while true; do

    # Seleccionar una imagen aleatoria
    INDEX=$(shuf -i 0-$((${#WALLPAPERS[@]} - 1)) -n 1)
    IMAGE="${WALLPAPERS[$INDEX]}"

    # echo "Nuevo fondo: $IMAGE"

    # Iniciar el nuevo fondo
    swaybg -o "$OUTPUT" -i "$IMAGE" -m fill &
    NEW_PID=$!

    # Cerrar el fondo anterior
    if [ -n "$CURRENT_PID" ]; then
        kill "$CURRENT_PID" 2>/dev/null || true
        wait "$CURRENT_PID" 2>/dev/null || true
    fi

    CURRENT_PID="$NEW_PID"

    # Esperar 10 minutos
    sleep "$INTERVAL"

done