#!/bin/bash
#Created by CharlesV and Melber from MX Linux Forum
#Modded for AV Linux and MX Moksha by AVLinux

# Selected folder from Thunar
TARGET_FOLDER="$1"

# If not a valid directory, exit
if [ ! -d "$TARGET_FOLDER" ]; then
    yad --error --title="YT-DLP Helper Error!" --window-icon=youtube --image=dialog-error \
    --center --width=640 --no-buttons  \
    --text="Target folder is not valid: $TARGET_FOLDER"
    exit 1
fi

# Prompt for video URL and file name
get_url_and_name=$(yad --title="YT-DLP Helper" --class=ytdlh \
--center --width=640 --height=220 --borders=20 \
--window-icon=youtube --image=youtube \
--form --columns=1 --separator=" " \
--button="Save Video!gtk-save" \
--text="\nDownload Youtube Video\n" \
--field="Paste the youtube video URL":LBL " " \
--field=" " "url" \
--field="Save as (file name without extension)":LBL " " \
--field=" " "filename" 
)

case "$?" in
    252 )
    exit 0
    ;;
esac

yad_array=($get_url_and_name)

URL="${yad_array[0]}"
FILE_NAME="${yad_array[@]:1}"

[ -z "$URL" ] && exit 1
[ -z "$FILE_NAME" ] && exit 1

# Output path
OUTPUT_TEMPLATE="${TARGET_FOLDER}/${FILE_NAME}.%(ext)s"

# Run yt-dlp (output goes to text-info window)
$HOME/.local/bin/yt-dlp -o "$OUTPUT_TEMPLATE" "$URL"  2>&1 | \
`yad \
 --text-info \
 --text="<b>Progress Viewer</b>" \
 --fontname="16px Cantarell" \
 --wrap \
 --tail \
 --image="youtube" \
 --image-on-top \
 --center \
 --width=700 \
 --height=800 \
 --margins=20 \
 --button="Exit!gtk-close":0 \
 --window-icon="youtube" \
 --title="YT-DLP Helper"`

exit 0
