summaryrefslogtreecommitdiff
path: root/randomjournalpage.sh
blob: 727d1485cb851f5f2de6d4e3bd943fc79a28e722 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env bash

declare -r ARG="$1"

# From my NextCloud sync folder :-)
declare -r JOURNAL_DIR="$HOME/Journals"
# Storing extract back to the NextCloud sync folder so that I can also read it 
# from my smartphone! :-)
declare -r OUT_PDF=$JOURNAL_DIR/random_journal_extract.pdf
declare -i NUM_PAGES_TO_EXTRACT=42 # This is the answear!
declare -r PDF_VIEWER_COMMAND=/usr/bin/evince

get_random_journal () {
    find "$1" -name \*.pdf | grep -v random_journal_extract | sort -R | head -n 1
}

extract () {
    local -r in_pdf="$1"; shift
    local -i from="$1"; shift
    local -i to="$1"; shift
    local -r out_pdf="$1"; shift

    echo "Extracting pages ${from}-${to} from $in_pdf to $out_pdf"
    qpdf --empty --pages "$in_pdf" "${from}-${to}" -- "$out_pdf"
    chmod 600 "$out_pdf"
}

main () {
    local -r random_journal=$(get_random_journal "$JOURNAL_DIR")
    local -i num_pages=$(pdfinfo "$random_journal" | awk '/Pages/ { print $2 }')

    local -i extract_from=$(( 1 + (RANDOM % num_pages) - NUM_PAGES_TO_EXTRACT ))
    if [ $extract_from -lt 1 ]; then
        extract_from=1
    fi

    local -i extract_to=$(( extract_from + NUM_PAGES_TO_EXTRACT -1 ))
    if [ $extract_to -gt "$num_pages" ]; then
        extract_to=$num_pages
    fi

    extract "$random_journal" "$extract_from" "$extract_to" "$OUT_PDF"
    if [ "$ARG" != cron ]; then
        $PDF_VIEWER_COMMAND "$OUT_PDF"
    fi
}

main