#!/bin/bash

#pvid: streamlink wrapper

print_help() {
	echo "A streamlink wrapper"
	echo ""
	echo "Usage:   emp [options] url"
	echo ""
	echo "Options:"
	echo "   -h, --help    Print this help text"
	echo "   -b, --bg      Play the video on the root window"
	echo "   -a, --audio   Play only the audio"
	echo ""
	exit 0
}

short_args=hba
long_args=help,bg,audio

# default
default_stream="best"
mpv_cmd="mpv"
player_args="--wid="$(xdotool getactivewindow)""
streamlink_args="--retry-stream 30"

# Parse arguments
parsed_args=$(getopt --options $short_args --longoptions $long_args --name "$0" -- "$@")
if [[ $? -ne 0 ]]; then
	echo "Failed to parse arguments"
	exit 2
fi
eval set -- "$parsed_args"
while true; do
	case "$1" in
		-h|--help)
			print_help
			;;
		-b|--bg)
            a=y
            streamlink_args="$streamlink_args --quiet"
			mpv_cmd="xwinwrap -ov -fs -- mpv"
            player_args="--no-osc --wid WID"
			shift
			;;
		-a|--audio)
            a=y
            streamlink_args="$streamlink_args --quiet"
            player_args="--no-video"
			shift
			;;
		--)
			shift
			break
			;;
		*)
			#the following args will be passed to streamlink
			break
			;;
	esac
done

if [[ -z "$@" ]]; then
	print_help
fi

streamlink \
    $streamlink_args \
    --default-stream "$default_stream" \
    --player="$mpv_cmd" \
    --player-args "$player_args -- {filename}" \
    $@ &

if [[ -n "$a" ]]; then
    cava
fi

wait
exit $?