#!/bin/sh
set -euC

## Set `pidfile`
pidfile="${XDG_RUNTIME_DIR:-"/var/run/user/$(id -u)"}/background.pid"

## Kill any running daemon
if [ -r "$pidfile" ]
then
  pid="$(cat "$pidfile")"
  kill -- "-$pid"
  while kill -0 "$pid" 2> '/dev/null' ; do : ; done
fi

## Exit early if only killing
if [ "$1" = '--kill' ]
then
  exit 0
fi

## Set up `pidfile`
printf '%s' "$$" >| "$pidfile"
trap 'rm "$pidfile"' EXIT
trap 'exit 0' INT TERM

## Set background
nice \
  xwinwrap -fs -fdt -ov -un -b -s -st -sp -ni -nf -- \
  mpv \
    -wid WID \
    --really-quiet \
    --no-audio \
    --panscan=1 \
    --loop-file=inf \
    --ytdl-format='bestvideo[height<=?720][fps<=?30]' \
    "$@" \
  2> '/dev/null'
