#!/usr/bin/env bash
# download a file if it does not exist in the archive alread
# otherwise just re-link it from the archive

DL_FOLDER="${DL_FOLDER:-${XDG_VIDEOS_DIR:-$HOME/videos}}/inbox"
ARCHIVE_FOLDER="${ARCHIVE_FOLDER:-${XDG_VIDEOS_DIR:-$HOME/videos}}/archive"
YT_DL_CMD="${YT_DL_CMD:-yt-dlp}"
yt_default_opts=(-f "best[height\<=1080]" --retries 15 --embed-subs --sub-lang "en,de,es,fr")
declare -a YT_DL_OPTS=${YT_DL_OPTS:-( "${yt_default_opts[@]}" )}
YT_DL_TITLE="""${YT_DL_TITLE:-%(channel)s_%(title)s_%(id)s}"""

show_help() {
    printf """
archive.sh: Hard linking your stuff.
vidl: Video downloader

Simple wrapper for youtube-dl (or yt-dlp or similar). 

Usage:  vidl [OPTION] <link>

Point it to a link you want downloaded.

Options:

	-h		Display this help.

	-d		Directory to check for existence of file and archive to if needed.

	-f		Directory to download to.

    -t      Point to youtube-dl command to use. Can be command or absolute link.
            By default will use \`yt-dlp\` which is a more up to date fork of the 
            program.
"""
}

while getopts "t:f:d:h" opt; do
    case "$opt" in
    # v)  verbose=1
    # ;;
    f)
        DL_FOLDER="$OPTARG"
        ;;
    t)
        YT_DL_CMD="$OPTARG"
        ;;
    d)
        ARCHIVE_FOLDER="$OPTARG"
        ;;
    h | \? | *)
        show_help
        exit 0
        ;;
    esac
done
shift $((OPTIND - 1))

_call_archive() {
    command -v archive >/dev/null 2>&1 || {
        echo "archive command not found."
        exit 1
    }
    archive -d "$2" -a "$1"
}

vid_ext="\(mp4\|avi\|webm\|mkv\|mpe?g\|3gp\|m4a\)"
_findfile() {
    dir="$1"
    fname="$2"
    find "$dir" -type f -name "$fname.*" | sed -ne "/$fname\.$vid_ext$/Ip"
}

YT_DL_TITLE="%(channel)s_%(title)s_%(id)s"
_download() {
    "$YT_DL_CMD" \
        -o "$DL_FOLDER/$YT_DL_TITLE.%(ext)s" \
        "${YT_DL_OPTS[@]}" \
        "$url"
}

url="$*"
dl_fn=$("$YT_DL_CMD" --get-filename -o "$YT_DL_TITLE" "$url")
video_file_regex="${dl_fn}"

if [ -z "$dl_fn" ]; then
    echo Could not get video filename, error with youtube-dl.
    exit 1
fi

alreadyexists=$(_findfile "$ARCHIVE_FOLDER" "$video_file_regex")

# # download the video to download folder
if [ "$alreadyexists" = "" ] || [ -z "$alreadyexists" ]; then
    _download

    # yt-dl never knows the exact filename in advance
    file=$(_findfile "$DL_FOLDER" "$video_file_regex")
    if [ -z "$file" ]; then exit 1; fi
    _call_archive "$file" "$ARCHIVE_FOLDER"
# only link old file if one exists
else
    echo "$alreadyexists" | while read -r file; do
        echo "file $file exists, not downloading duplicate"
        _call_archive "$file" "$DL_FOLDER"
    done
fi