#!/bin/bash

# This code requires that you have yt-dlp installed. Check the FAQ on how to install it.
# yt-dlp is assumed to reside in your Downloads folder.
# Documents/Archive is where the collection will be downloaded, verify that files are indeed there.

ArchivePath="$HOME/Documents/Archive"
ytdlCommand="$HOME/Downloads/yt-dlp"
ytdlCommand="/mnt/c/Users/u.abdulhag/Downloads/yt-dlp.exe"


read -p "Paste the collection URL here: " link

# Extract sheetID from the collection URL
IFS='/' read -ra url_parts <<< "$link"
length=${#url_parts[@]}
if [ $length -ge 6 ]; then
    sheetID=${url_parts[5]}
else
    sheetID=$(echo "${url_parts[4]}" | cut -d'=' -f2)
fi

#echo $sheetID
#exit
GvizCSVURL="https://docs.google.com/spreadsheets/d/$sheetID/gviz/tq?tqx=out:csv&tq=SELECT%20*"

response=$(curl -s -o /dev/null -w "%{http_code}" $GvizCSVURL)

if [ $response -eq 200 ]; then
    echo "Request successful"
    content=$(curl -s $GvizCSVURL)
    # Process the content as needed
else
    echo "Request failed with status code: $response, are you sure it is 'Shared'"
fi

# Create a file-like object from the CSV content
link_column_index=$(echo "$content" | head -n1 | tr ',' '\n' | grep -n '^"Link"$' | cut -d ':' -f1)
csv_file=$(echo "$content" | sed 's/\\//g' | tail -n +2)

# Create a while loop to iterate over each line in the CSV file
while IFS=',' read -r Link ; do
     $ytdlCommand --download-archive allCollections.txt $(echo $Link|cut -f$link_column_index -d,| sed 's/^\(\"\)\(.*\)\(\"\)/\2/g')
    # Run the external command
done <<< "$csv_file"
