#!/usr/bin/env bash
# https://gist.github.com/Strayer/7989654/raw/dd24cf84ede5daa66459dbffe027129994da4ef4/youtube-dl-dash.bash
#                       /usr/local/bin/youtube-dl-dash
#  http://crystalfaeries.net/posix/bin/youtube-dl-dash
# celeste:crystalfaery 2016-02-05 03:16:07+00:00
set -e

YOUTUBE_FORMATS=$(youtube-dl -F "$1")

if [[ "$YOUTUBE_FORMATS" == *"(DASH Video)"* ]]; then
    VIDEO_NAME=$(youtube-dl --get-filename "$1")
    VIDEO_NAME_TMP="$VIDEO_NAME.tmp"

    echo "Filename: $VIDEO_NAME"

    if [ -e "$VIDEO_NAME" ]; then
        echo "File already exists, aborting..."
        exit
    fi

    # Strip dashes from the beginning of the ID to avoid command line errors
    VIDEO_ID=`youtube-dl --get-id "$1" | sed "s/^-/_/"`

    VIDEO_FORMAT=`echo "$YOUTUBE_FORMATS" | fgrep "(DASH Video)" | head -n 1`
    VIDEO_FORMAT_ID=`echo "$VIDEO_FORMAT" | cut -f 1`
    VIDEO_FORMAT_NAME=`echo "$VIDEO_FORMAT" | cut -f 4,5`

    AUDIO_FORMAT=`echo "$YOUTUBE_FORMATS" | fgrep "(DASH Audio)" | head -n 1`
    AUDIO_FORMAT_ID=`echo "$AUDIO_FORMAT" | cut -f 1`
    AUDIO_FORMAT_NAME=`echo "$AUDIO_FORMAT" | cut -f 4,5`

    echo "Using formats: $VIDEO_FORMAT_NAME, $AUDIO_FORMAT_NAME"

    youtube-dl -f $VIDEO_FORMAT_ID -o "${VIDEO_ID}.vid" "$1"
    youtube-dl -f $AUDIO_FORMAT_ID -o "${VIDEO_ID}.aud" "$1"

    echo -n "Combining files..."
    
    ffmpeg -i "$VIDEO_ID.vid" -i "$VIDEO_ID.aud" -c copy -f mp4 -v warning \
        "$VIDEO_NAME_TMP"
#   rm "$VIDEO_ID".*
    mv "$VIDEO_NAME_TMP" "$VIDEO_NAME"
    
    echo " done!"
else
    youtube-dl "$1"
fi


syntax highlighted by Code2HTML, v. 0.9.1