#!/bin/bash

echo "Ce programme télécharge les vidéos youtube."

set -e

yt-dlp -j --flat-playlist --socket-timeout 10 $(cat ~/Ressources/Divscripts/ytdl/channel_lists/Channels.txt) | jq -r '.id' | sed 's_^_https://youtube.com/v/_' > ~/Ressources/Divscripts/ytdl/util/vidsurls.txt
if [ $? -ne 0 ]; then
    echo "An error occurred while getting the video URLs."
    exit 1
fi

comm -23 <(sort ~/Ressources/Divscripts/ytdl/util/vidsurls.txt) <(sort ~/Ressources/Divscripts/ytdl/util/vidsurlsArchive.txt) > ~/Ressources/Divscripts/ytdl/diffs/diff.txt
if [ $? -ne 0 ]; then
    echo "An error occurred while calculating the difference between the video URLs."
    exit 1
fi

yt-dlp -cw --hls-prefer-native --write-description --write-link --write-thumbnail --ignore-errors --embed-chapters --embed-thumbnail --socket-timeout 10 --download-archive ~/Ressources/Divscripts/ytdl/archives/Archive.txt --output '/home/storage/INLET/Youtube/Videos/English/%(uploader)s/%(upload_date)s-%(title)s/%(title)s.%(ext)s' -f "bestvideo[height<=480]+bestaudio/best[height<=480]" $(cat ~/Ressources/Divscripts/ytdl/diffs/diff.txt)
if [ $? -ne 0 ]; then
    echo "An error occurred while downloading the videos."
    exit 1
fi

cat ~/Ressources/Divscripts/ytdl/diffs/diff.txt >> ~/Ressources/Divscripts/ytdl/util/vidsurlsArchive.txt && echo Videos Program has ended