#!/bin/sh

# random_wallpaper.sh
# 2020-03-28
# by Gernot Walzl

DISPLAY=${DISPLAY:-':0.0'}
WALLPAPER_DIR=${WALLPAPER_DIR:-'/usr/share/rpd-wallpaper'}
SLEEP_SECS=${SLEEP_SECS:-'3600'}

daemon () {
  local WALLPAPER_JPG
  while :; do
    sleep "$SLEEP_SECS"
    WALLPAPER_JPG=$(find "$WALLPAPER_DIR" -type f -name '*.jpg' | shuf -n1)
    DISPLAY="$DISPLAY" pcmanfm --set-wallpaper="$WALLPAPER_JPG"
  done
}

install () {
  local LXS_PROFILE_DIR='/home/pi/.config/lxsession/LXDE-pi'
  if [ ! -f "$LXS_PROFILE_DIR/autostart" ]; then
    mkdir -p "$LXS_PROFILE_DIR"
    cp /etc/xdg/lxsession/LXDE-pi/autostart "$LXS_PROFILE_DIR"
  fi
  if ! grep random_wallpaper "$LXS_PROFILE_DIR/autostart" ; then
    echo "@scripts/random_wallpaper.sh" >> "$LXS_PROFILE_DIR/autostart"
  fi
}

case "$1" in
  'install') install ;;
  *) daemon ;;
esac