#!/usr/bin/env bash

# random_wallpaper
#
# Requirement: feh (apt install feh)

directory="$HOME/wallpapers"
minutes=15
PROGRAM=`which feh`
is_wayland=false

# Some tests
if [[ "${XDG_SESSION_TYPE}" == "wayland" ]]; then
  PROGRAM=`which swaymsg`
  if [ -z "${PROGRAM}" ]; then
    echo "This script needs the swaymsg program."
    exit 1
  fi
  is_wayland=true
elif [ -z "${PROGRAM}" ]; then
  echo "This script needs the feh program. Install it."
  exit 1
fi

if [ -d '$directory' ]; then
  echo "No $directory found."
  exit 1
fi

IFS="
"

array_files=($(ls -1 $directory))

nb_files=`ls $directory|wc -l`

if [ $nb_files == 0 ]; then
  echo "$nb_files files in $directory"
  exit 1
fi

# initialisation
seconds=$[ $minutes * 60 ]

while true; do

  # Random number generator (not more than files number)
  NUMBER=$[ ( $RANDOM % $nb_files ) ]

  # Change background
  file="${array_files["$NUMBER"]}"
  if "${is_wayland}"; then
    $PROGRAM output "*" bg "$directory/$file" fill
  else
    feh --bg-fill "$directory/$file"
  fi

  # Wait some times
  sleep $seconds
done

exit 0