#!/usr/bin/zsh

function multigrep () {
    if  [[ $# -ge 3 ]]; then
	grep -i "$1" =(multigrep "${@[2,-1]}")
    else
	grep -i "$@"
    fi
}

echo "$1"|grep -q .epub$ && {
    calibre_output="$(calibredb add "$1" 2>&1)"
    book_id="$(echo "$calibre_output"|cut -d\  -f 4)"
    echo $book_id|grep -q '^[0-9][0-9]*$' || book_id=$(calibredb -w 1000 list -s "title:$(echo "$calibre_output"|sed -n '2s/^  //p')"|sed -n '1s/ .*//p')
} || book_id=$(multigrep $* =(calibredb -w 1000 list) |cut -d\  -f1)

calibre_path=~/Calibre\ Library/"$(sqlite3 ~/Calibre\ Library/metadata.db "select path from books where id like $book_id")"

find "$calibre_path" |grep -q .pdf$ || {
    pandoc -t context --pdf-engine=context --template raddread -s -o /tmp/my-visp-${book_id}.pdf "$(find "$calibre_path" |grep .epub$)"
    calibredb add_format $book_id /tmp/my-visp-${book_id}.pdf
    rm /tmp/my-visp-${book_id}.pdf
}

cp "$(find "$calibre_path" |grep .pdf$)" ~/raddjuret/
#mupdf-gl "$(find "$calibre_path" |grep .pdf$)"
