#!/bin/sh
set -euC

##/// background 1.0
#////
#//// Set X Window System background image/video.
#////
###// usage:
#////   background [-v|--video] [--] [<path>]
#////   background -h|--help
#////   background --version
#////
###// options:
####/   -v, --video
#////     Changes the default <path> to
#////     ${XDG_DATA_HOME:-$HOME/.local/share}/backgrounds-video.
###// arguments:
####/   <path>
#////     If not a directory, set it as background. If a directory, search
#////     recursively in it (resolving symlinks) and set a random file as
#////     background.
#////     [default: ${XDG_DATA_HOME:-$HOME/.local/share}/backgrounds]

## Messages
prog="$(basename "$0")"
help()    { sed -n 's|^#[#/]*/ \?||p' "$0";                 exit 0; }
version() { help | awk '/^$/{++p;next}p==0';                exit 0; }
usage()   { help | awk '/^$/{++p;next}p==2';                exit 0; }
parse()   { printf '%s: error: %s\n'   "$prog" "$1"; usage; exit 1; } >&2
error()   { printf '%s: error: %s\n'   "$prog" "$1";        exit 1; } >&2
warning() { printf '%s: warning: %s\n' "$prog" "$1";                } >&2
opt()     { [ $# -gt 1 ] || parse "option '$1' value not provided"; }
arg()     { [ $# -gt 1 ] || parse "argument '$1' not provided";     }
argend()  { [ $# -eq 0 ] || parse "argument '$1' not recognized";   }
dep()     { [ "$(command -v "$1")" ] || error "'$1' not available"; }

## Parse special options
case "${1:-}"
in
  '-h'|'--help') help; ;;
  '--version') version; ;;
esac

## Parse options
suffix=''
while [ $# -gt 0 ]
do
  case "$1"
  in
    '-v'|'--video') suffix='-video'; shift; ;;
    '--') shift; break; ;;
    *) break; ;;
  esac
done

## Parse optional arguments
path="${XDG_DATA_HOME:-"$HOME/.local/share"}/backgrounds${suffix}"
[ $# -eq 0 ] || { path="$1"; shift; }

## Parse unrecognized arguments
argend "$@"

## Convert `path` from directory to file if needed
if [ -d "$path" ]
then
  path="$(find -L "$path" \! -type d | shuf -n 1)"
fi

## Set `daemon`
daemon="$(dirname "$0")/../libexec/background/daemon"

## Opportunistically use `hsetroot` for images
if [ "$(command -v xdg-mime)" ] && [ "$(command -v hsetroot)" ]
then
  if xdg-mime query filetype "$path" | grep -q '^image/'
  then
    "$daemon" --kill
    hsetroot -cover "$path"
    exit 0
  fi
fi

## Run daemon
setsid "$daemon" "$path" &
