#!/bin/sh

BASE=/home/kara

# Extract all fonts from the MKV file ($1)
function extract_fonts ()
{
    STA=0
    IDX=0
    while [ $STA -eq 0 ] ; do
        IDX=$[ $IDX + 1 ]
        mkvextract "$1" attachments "$IDX:/tmp/fontfile$IDX.ttf" 2>/dev/null >/dev/null
        STA=$?
    done
    return $IDX
}

# Update attachments with the right type MIME, $1 is the MKV file, $2 is the id of the attachments
function update_attachments ()
{
    mkvpropedit "$1" --attachment-mime-type application/x-truetype-font --update-attachment "$2" 2>/dev/null >/dev/null
}

function update_kara_main ()
{
    [ -z "$1" ] && return 1

    # Get if there are fonts as attachments in the MKV
    FILE=$(mkvinfo -t "$1" | grep -iE 'ttf|otf' 2>/dev/null | grep -oE '[^ ]+$')
    STA=$?

    ! [ $STA -eq 0 ] && return 1

    extract_fonts "$1"
    COUNT=$[ $? - 1 ]
    while [ $COUNT -gt 0 ] ; do
        update_attachments "$1" "$COUNT"
        COUNT=$[ $COUNT - 1 ]
    done
    echo "$1"
}

if [ -z "$1" ] ; then
  find $BASE -type f -name '*.mkv' -exec "$0" "{}" \;
else
  update_kara_main "$1"
fi