#!/bin/bash
#
# Copyright (C) 2023-2025 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-1440 tries to download the video with a frame height of 1440 pixels.
yt-2160 tries to download the video with a frame height of 2160 pixels.
yt-a downloads audiotrack only.

Usage:
    ${0##*/} [-D] <URL> [-o <output-file>] [yt-dlp options...]

Flag '-D' enables upload date to the output file name.
Flags (now only '-D') must precede the 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_SCRIPT="$(dirname -- "${BASH_SOURCE[0]}")/bbsi-version"
    if [[ ! -x "$VERSION_SCRIPT" ]]; then
        echo "Unknown version."
    else
        "$VERSION_SCRIPT"
    fi
}


# The function prints information about wrong usage to stderr.
Wrong_Usage() {
    echo "Wrong usage. See: ${0##*/} --help" >&2
}


# 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
DATE_ENABLED=FALSE
CUSTOM_PATH=""
OPT_TEMP=$(getopt -o 'Do:' -n "$0" -- "$@")
if [[ $? -ne 0 ]]; then
    Wrong_Usage
    exit 1
fi
eval set -- "$OPT_TEMP"
unset "$OPT_TEMP"
while true; do
    case "$1" in
        '-D')
            DATE_ENABLED=TRUE
            shift
            continue
            ;;
        '-o')
            CUSTOM_PATH="$2"
            shift 2
            continue
            ;;
        '--')
            shift
            break
            ;;
        *)
            echo "Internal error" >&2
            exit 1
    esac
done

if [[ $# -eq 0 ]]; then
    Wrong_Usage
    exit 1
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
if ! command -v "$UTIL" &>/dev/null ; then
    BBSI_CACHE_DIR=~/.cache/bbsi
    PYTHON_ENV="${BBSI_CACHE_DIR}/python_env"
    mkdir -p "${PYTHON_ENV}"
    virtualenv "${PYTHON_ENV}"
    source "${PYTHON_ENV}/bin/activate"
    readonly SIGS="EXIT HUP INT TERM ERR"
    trap deactivate $SIGS
    pip3 install --upgrade yt-dlp
fi
if [[ -z "$CUSTOM_PATH" ]]; then
    FMT="%(title)s.%(ext)s"
else
    FMT="$CUSTOM_PATH"
fi
if [[ "$DATE_ENABLED" == TRUE ]]; then
    FMT="%(upload_date)s - $FMT"
fi
URL="$1"
shift

SCRIPT_NAME="${0##*/}"
YT="$(dirname "$0")/yt"
if [[ "$SCRIPT_NAME" == yt-a ]]; then
    "$UTIL" -x "$URL" -o "$FMT" -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
