#!/usr/bin/env bash

WALLPAPER_DIR="$HOME/Pictures/Wallpapers/current/"
INTRO_DIR="$HOME/Pictures/Wallpapers/intro/"
DELAY=5m

random_wallpaper() {
  # Check if folder is not empty
  if [ -z "$(ls -A "$WALLPAPER_DIR")" ]; then
    echo "Current wallpaper folder is empty, nothing to do"
    exit 0
  fi

  CURRENT_WALL=$(hyprctl hyprpaper listloaded)

  # Get a random wallpaper that is not the current one
  WALLPAPER=$(find "$WALLPAPER_DIR" -type l ! -name "$(basename "$CURRENT_WALL")" | shuf -n 1)

  # Apply the selected wallpaper
  swww img -o $1 "$WALLPAPER"

  if [ $? -ne 0 ]; then
      echo "The previous command failed."
      return 1
  fi

  echo "Set random wallpaper for $1 to $WALLPAPER"
}

loop() {
  sleep 1
  while true; do
    if [ ! $(cat $HOME/.config/hypr/conditions/lock_wallpaper) -eq 1 ]; then
        random_wallpaper "eDP-1" &
        sleep 1
        random_wallpaper "HDMI-A-1" &
    fi
    sleep "$DELAY"
  done
}

if [[ $1 = "random" ]]; then
    random_wallpaper "eDP-1" &
    sleep 1
    random_wallpaper "HDMI-A-1" &
    exit 0
elif [[ -z $1 ]]; then
    loop
else
    echo "Error: unknown command '$1'"
    exit 1
fi
