#!/bin/bash
#
# Copyright (C) 2023 Eugene 'Vindex' Stulin
# Distributed under the Boost Software License 1.0.

set -eu -o pipefail

# The function prints help information.
Print_Help() {
cat <<EndOfHelp
This script downloads video from video platforms using yt-dlp.
Main page of yt-dlp:
https://github.com/yt-dlp/yt-dlp

This wrapper sets a special name format for downloaded files:
name stores upload date and title.

yt uses default quality.
yt-360 tries to download the video with a frame height of 360 pixels.
yt-480 tries to download the video with a frame height of 480 pixels.
yt-720 tries to download the video with a frame height of 720 pixels.
yt-1080 tries to download the video with a frame height of 1080 pixels.
yt-a downloads audiotrack only.

Usage:
    $0 [options] <URL> 

Additional arguments will be passed to the yt-dlp call.

Help and version:
    $0 --help|-h
    $0 --version|-v
EndOfHelp
}


# The function prints the script version.
Print_Version() {
    local version_file="$(dirname -- "${BASH_SOURCE[0]}")/bbsi_version"
    local vers
    vers="$(cat "$version_file" 2>/dev/null)" || vers="is unknown"
    echo "Bash-based set of instruments (bbsi), version $vers."
}


# parse command line arguments
if [[ $# -eq 1 ]]; then
    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        Print_Help
        exit 0
    elif [[ "$1" == "-v" || "$1" == "--version" ]]; then
        Print_Version
        exit 0
    fi
fi


Interrupt_Execution() {
    set +x
    echo "The script has been interrupted." 2>&1
    exit 1
}
trap Interrupt_Execution ABRT INT QUIT TERM


UTIL=yt-dlp
FMT="%(upload_date)s - %(title)s.%(ext)s"
URL="$1"
shift

SCRIPT_NAME="${0##*/}"
YT="$(dirname "$0")/yt"
if [[ "$SCRIPT_NAME" == yt-a ]]; then
    "$UTIL" -x "$URL" -o "%(upload_date)s - %(title)s.%(ext)s" -f bestaudio
elif [[ "$SCRIPT_NAME" == yt-2160 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=2160]+bestaudio/best"
elif [[ "$SCRIPT_NAME" == yt-1440 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=1440]+bestaudio/best"
elif [[ "$SCRIPT_NAME" == yt-1080 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=1080]+bestaudio/best"
elif [[ "$SCRIPT_NAME" == yt-720 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=720]+bestaudio/best"
elif [[ "$SCRIPT_NAME" == yt-480 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=480]+bestaudio/best"
elif [[ "$SCRIPT_NAME" == yt-360 ]]; then
    "$YT" "$URL" $@ -f "bestvideo[height<=360]+bestaudio/best"
else  # yt
    "$UTIL" "$URL" $@ -o "$FMT" --merge-output-format mp4 --embed-subs
fi
