#!/usr/bin/env bash

export DEFAULT_PLAYLIST_END=15
export DEFAULT_INC_STEP=10
export YT_TEMPLATE="${HOME}/Downloads/yt-dl/%(uploader)s/%(upload_date)s %(title)s.%(ext)s"

download() {
  youtube-dl "$1" \
             --download-archive ~/Nextcloud/Cache/youtube-dl-seen.conf \
             --prefer-free-formats                                     \
             --playlist-end "$2"                                       \
             --write-description                                       \
             --output "$YT_TEMPLATE"
}
export -f download


download_user() {
  download "https://www.youtube.com/user/$1" "${2-$DEFAULT_PLAYLIST_END}"
}
export -f download_user


download_channel() {
  download "https://www.youtube.com/channel/$1" "${2-$DEFAULT_PLAYLIST_END}"
}
export -f download_channel


download_playlist() {
  download "https://www.youtube.com/playlist?list=$1" "${2-$DEFAULT_PLAYLIST_END}"
}
export -f download_playlist

inc_download() {
  local fn="$1"
  local id="$2"
  local step="${3-$DEFAULT_INC_STEP}"

  local file="$HOME/.yt-db/$id"
  mkdir -p "$HOME/.yt-db"
  cat "$file" 2> /dev/null
  local n_count
  n_count="$(cat "$file" 2> /dev/null || printf 10)"
  local n_count_new="$((n_count + step))"

  echo "$n_count_new" > "$file"

  "$fn" "$id" "$n_count"
}

export -f inc_download
