# You will need yt-dlp, jq, and ffmpeg

yt-dlp --write-info-json --skip-download --output metadata $1
LINK=$(jq -r '.url' metadata.info.json)
BASELINK=${LINK:0:(-14)}
rm metadata.info.json

# Fragments are in 10s chunks

# Quickly download fragments until caught up.
I=0
while :
do
  wget "$BASELINK$I.ts" || break
  I=$((I+1))
done

# Sleep 11 instead of 10, just in case, so we don't run into timing errors.
# Probably not needed, but no harm in playing it safe.
sleep 11

# Once we're caught up we can take it slow.
while :
do
  wget "$BASELINK$I.ts" || break
  I=$((I+1))
  sleep 10
done

echo $((I+1)) "fragments found and downloaded"

echo "Merging fragments"
for i in `\ls *.ts | sort -V`; do echo "file '$i'"; done >> mylist.txt
ffmpeg -f concat -i mylist.txt -c copy -bsf:a aac_adtstoasc video.mp4
rm mylist.txt
