#!/bin/sh
CACHE=/tmp/preman

if [ ! $1 ]; then
    # give man's wtf error
    man
    exit
fi

# get manpage name
MANPAGE=`man -w $@`
if [ ! $? = 0 ]; then  # not found
    # man will have printed an error
    exit
fi

MANPAGE=`basename $MANPAGE`
PDF=$CACHE/$MANPAGE.pdf

# create cache if it doesn't exist
if [[ ! -d $CACHE ]]; then
    mkdir -p $CACHE
fi

# if there's no cached pdf, make one
if [[ ! -r $PDF ]]; then
    man -t $@ | pstopdf -i -o $PDF
fi

open $PDF