#!/usr/bin/env python

import os
import subprocess
import sys


find_cmd = "find {} -path '*.pdf'"
rofi_cmd = 'rofi -levenshtein-sort -dmenu -i -no-custom -p "book: " -format i'
open_cmd = "xdg-open '{}'"


if len(sys.argv) > 1 and sys.argv[1]:
    base = '~/school/books'
else:
    base = '~/school/books/current'

books = subprocess.check_output(find_cmd.format(base), shell=True).split('\n')
books = filter(None, books)

try:
    fnames = '\n'.join(map(os.path.basename, books))
    booknum = subprocess.check_output("echo '{}' | {}".format(fnames,
        rofi_cmd), shell=True)[:-1]
except subprocess.CalledProcessError: # pressed Esc or something at the prompt
    sys.exit(0)

cmd = open_cmd.format(books[int(booknum)])
subprocess.call(cmd, shell=True)

