#!/bin/sh
# dep: jj sed curl

domain='xxivproduction.video'
channel='lies_channel'
count=1 # set to 1 for get latest video from channel

peertube_api_get_channel_videos ()
{
	curl -S "https://$domain/api/v1/video-channels/$channel/videos?count=$count&skipCount=true"
}

peertube_api_get_video ()
{
	curl -S "https://$domain/api/v1/videos/$1"
}

echo 'Getting uuids...'
get_uuids=$(peertube_api_get_channel_videos | jj -l data.#.uuid | sed 's/"//g')
echo 'Done\n'

get_all_torrents ()
{
	echo 'Getting names and torrents'
	for uuid in $get_uuids; do
		echo $uuid
		video=$(peertube_api_get_video $uuid) 
		echo $video | jj name >> "$channel".txt
		echo $video | jj -l 'streamingPlaylists' | jj -l 'files.#.torrentUrl' | sed 's/"//g' >> "$channel".txt
		sleep 1
	done	
}

get_latest_torrent_video ()
{
	echo 'Getting name and torrent url...'
	for uuid in $get_uuids; do
		echo $uuid
		video=$(peertube_api_get_video $uuid) 
		echo $video | jj name >> temp_"$channel".txt
		echo $video | jj -l 'streamingPlaylists' | jj -l 'files.#.torrentUrl' | sed 's/"//g' >> temp_"$channel".txt
		cat "$channel".txt >> temp_"$channel".txt
		mv temp_"$channel".txt "$channel".txt
	done	
}

get_sizes ()
{
	echo 'Getting sizes...'
	for uuid in $get_uuids; do
		echo $uuid
		video=$(peertube_api_get_video $uuid) 
		echo $video | jj -l 'streamingPlaylists' | jj -l 'files.#.size' | sed 's/"//g' >> datasizes
	done
	awk '{s+=$1} END {printf "%.0f", s}' datasizes
}

if [ $count -ge 2 ]; then
get_all_torrents
elif [ $count -eq 1 ]; then
get_latest_torrent_video
fi
echo '\nDone'
