#!/usr/bin/env bash
export PERL_UNICODE=S

[[ -z ${PONYDIR} ]] && PONYDIR=/usr/share/ponies
HOMEDIR=${HOME}/.ponies

cmd=cowsay
[[ ${0} == *ponythink ]] && cmd=cowthink

function ponyf() {
    if [[ -f ${HOMEDIR}/${1}.pony ]]; then
        ${cmd} -f "${HOMEDIR}/${1}.pony" $@
    elif [[ -f ${PONYDIR}/${1}.pony ]]; then
        ${cmd} -f "${PONYDIR}/${1}.pony" $@
    else
        ponyr $@
    fi
}
function ponyr() {
    if [[ -d ${HOMEDIR} ]] && [[ -n $(find ${HOMEDIR} -name \*.pony) ]]; then
        ${cmd} -f $(ls ${HOMEDIR}/*.pony | sort -R | head -n1) $@
    elif [[ -d ${PONYDIR} ]] && [[ -n $(find ${PONYDIR} -name \*.pony) ]]; then
        ${cmd} -f $(ls ${PONYDIR}/*.pony | sort -R | head -n1) $@
    fi
}

while getopts f:hv OPT
do
    case ${OPT} in
	v)  echo "ponysay v0.2" ; exit;;
	h)  echo "-v for version, -h for this, -f to specify a ponyfile. It'll choose a random ponyfile if no argument is given." ; exit;;
	f)  ponyf $* ; exit;;
	\?) echo "DERP"; exit;;
	*)  ponyr $* ; exit;;
    esac
done
ponyr $*