#!/bin/bash
set -e

loc="$HOME/streamrips"
[ -z "$2" ] ||
	loc="$2"

which streamlink >/dev/null 2>/dev/null ||
{
	[ -e "$HOME/ve.streamlink" ] &&
		. ~/ve.streamlink/bin/activate ||
	{
		python3 -m venv ~/ve.streamlink
		. ~/ve.streamlink/bin/activate
		pip install streamlink
	}
}

[ -z "$1" ] &&
{
	echo "need argument 1: stream to rip"
	echo " optional arg 2: target folder"
	echo
	echo "checks for updates if arg1 is u"
	echo
	exit 1
}

[ "$1" = u ] &&
{
	pip install -U streamlink
	exit 0
}

mkdir -p "$loc"

has_been_up=
sleeptime=10
failures=0
streamurl="$1"
streamname="$(
	printf '%s\n' "$streamurl" |
	sed -r 's@.*/@@'
)"

while true
do
	echo
	streamloc="$loc/$streamname-$(date +%Y-%m%d-%H%M%S).ts"
	printf 'Recording [\033[36m%s\033[0m] to [\033[33m%s\033[0m]\n' "$streamname" "$loc"

	t0=$(date +%s)
	PYTHONUNBUFFERED=x streamlink --twitch-disable-hosting --force-progress "$1" best -o "$streamloc" 2>&1 |
	tee -a "$streamloc.log"
	
	t=$(date +%s)
	tdelta=$((t-t0))

	echo
	echo "Recorded $tdelta seconds"

	(( tdelta > 30 )) &&
		failures=0 &&
		has_been_up=1 &&
		sleeptime=10

	(( failures > 20 )) &&
		[ $has_been_up ] &&
			break

	echo "Stream ended or disconnected. Trying to restart recording in $sleeptime seconds"
	sleep $sleeptime
	
	failures=$((failures+1))
	sleeptime=$(((sleeptime*3)/2))
	[ $sleeptime -gt 90 ] &&
		sleeptime=96
done
