#!/bin/bash

shopt -s nullglob

export PATH="/home/transcoder/bin:/usr/local/bin:/usr/bin:/bin"

exec 9>/var/lock/mirror_youtube.sh
flock -n 9 || exit 1

cd /mnt/media/video/mirror/youtube

mirror(){
  for channel in */*/url
  do
    (
      set -x
      cd "$(dirname "$channel")"
      url="$(cat url)"

      # Regenerate downloaded list to remove entries from downloaded list which don't seam to actually be there
      for file in *.info.json
        do jq -r '.extractor+" "+.id' <"$file"
      done >downloaded.txt

      youtube-dl --download-archive downloaded.txt --no-post-overwrites -f "bestvideo+bestaudio/best" -ciw -o "%(title)s.%(ext)s" --xattrs --write-info-json --write-thumbnail -q "$url"
      chmod 644 -- *.info.json

      for video in *.mp4
      do
        name="$(printf '%s' "$video" | sed 's/\.[^.]*$//')"
        if printf '%s' "$name" | grep -q '\.[0-9]\+$'
          then continue
        fi
	width="$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$video")"
        OPTS=()
	if [ -n "$width" ]
        then
          if [ "$width" -gt 2000 ] && ! [ -f "$name.1920.mp4" ]
            then OPTS+=(-map 0:v:0 -map 0:a -c:v h264 -c:a aac -vf scale=1920:-2 -movflags faststart "$name.1920.mp4")
          fi
          if [ "$width" -gt 1400 ] && ! [ -f "$name.1280.mp4" ]
            then OPTS+=(-map 0:v:0 -map 0:a -c:v h264 -c:a aac -vf scale=1280:-2 -movflags faststart "$name.1280.mp4")
          fi
        fi
        if [ "${#OPTS[@]}" -gt 0 ]
        then
          if ! ffmpeg -y -i "$video" "${OPTS[@]}"
            then rm -f "$name".*.mp4
          fi
        fi
      done &

      for video in *.ogg *.webm *.mkv
      do
	width="$(ffprobe -v error -select_streams v:0 -show_entries stream=width -of csv=p=0 "$video")"
        name="$(printf '%s' "$video" | sed 's/\.[^.]*$//')"
        OPTS=()
	if [ -n "$width" ]
        then
          if [ "$width" -gt 2000 ] && ! [ -f "$name.1920.mp4" ]
            then OPTS+=(-map 0:v:0 -map 0:a -c:v h264 -c:a aac -vf scale=1920:-2 -movflags faststart "$name.1920.mp4")
          fi
          if [ "$width" -gt 1400 ] && ! [ -f "$name.1280.mp4" ]
            then OPTS+=(-map 0:v:0 -map 0:a -c:v h264 -c:a aac -vf scale=1280:-2 -movflags faststart "$name.1280.mp4")
          fi
        fi
        if ffmpeg -y -i "$video" -map 0:v:0 -map 0:a -c:v h264 -c:a aac -movflags faststart "$name.mp4" "${OPTS[@]}"
          then rm -f "$video"
          else rm -f "$name.mp4" "$name".*.mp4
        fi
      done &

      sleep 60

#      youtube-dl --no-post-overwrites -f best -ciw -o "%(title)s.%(ext)s" --skip-download --xattrs --write-info-json --write-thumbnail -q "$url"

    )
  done
}

find -iname "*.part" -delete
mirror
