You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.2 KiB
Bash
106 lines
2.2 KiB
Bash
#!/usr/bin/env bash
|
|
|
|
usage() {
|
|
cat <<EOF
|
|
usage $0 [-d|r][-f][-h]
|
|
-d, --daily get the QOTD
|
|
-r, --random get a random quote
|
|
-p, --pager use pager to prevent quitting until keypress
|
|
-f, --force force update the quote pool
|
|
-h, --help display this message
|
|
EOF
|
|
}
|
|
|
|
API="https://zenquotes.io/api"
|
|
WORKING_DIR="$HOME/.local/share/quotes"
|
|
|
|
# create directory on fresh installs
|
|
if [ ! -d "$WORKING_DIR" ] ; then
|
|
mkdir -p "$WORKING_DIR"
|
|
fi
|
|
|
|
cd "$WORKING_DIR"
|
|
|
|
daily() {
|
|
TODAY=$(date +%m-%d)
|
|
|
|
if [ ! -f "daily_$TODAY.json" ] ; then
|
|
# prevent multiple requests per day
|
|
rm daily_*.json
|
|
curl -fs "$API/today" | gojq '.[0]' > "daily_$TODAY.json"
|
|
fi
|
|
|
|
cat "daily_$TODAY.json"
|
|
}
|
|
|
|
random() {
|
|
# have to be careful not to exceed 10 requests per minute
|
|
curl -fs "$API/random" | gojq '.[0]'
|
|
}
|
|
|
|
get_quote() {
|
|
if [ "$1" == "today" ] ; then
|
|
daily
|
|
elif [ "$1" == "random" ] ; then
|
|
random
|
|
else
|
|
if [[ ! -f "quotes.json" || "$UPDATE" == true ]] ; then
|
|
# update quotes file
|
|
curl -fs "$API/quotes" > quotes.json
|
|
fi
|
|
|
|
num=$(($RANDOM % 49))
|
|
cat quotes.json | gojq ".[$num]"
|
|
fi
|
|
}
|
|
|
|
# parse long form
|
|
for arg in "$@"; do
|
|
shift
|
|
case "$arg" in
|
|
'--help') set -- "$@" '-h' ;;
|
|
'--random') set -- "$@" '-r' ;;
|
|
'--daily') set -- "$@" '-d' ;;
|
|
'--pager') set -- "$@" '-p' ;;
|
|
'--force') set -- "$@" '-f' ;;
|
|
*) set -- "$@" "$arg" ;;
|
|
esac
|
|
done
|
|
|
|
# parse args
|
|
while getopts "hrdfp" opt ; do
|
|
case "$opt" in
|
|
'h')
|
|
usage
|
|
exit 0
|
|
;;
|
|
'r')
|
|
[ -n "$TYPE" ] && usage 1 || TYPE="random"
|
|
;;
|
|
'd')
|
|
[ -n "$TYPE" ] && usage 1 || TYPE="today"
|
|
;;
|
|
'f')
|
|
UPDATE=true
|
|
;;
|
|
'p')
|
|
PAGE=true
|
|
;;
|
|
'?')
|
|
usage
|
|
exit 1
|
|
;;
|
|
esac
|
|
done
|
|
|
|
QUOTE=$(get_quote "$TYPE")
|
|
|
|
Q=$(echo "$QUOTE" | gojq '.q' | tr -d '"')
|
|
A=$(echo "$QUOTE" | gojq '.a' | tr -d '"')
|
|
|
|
if [ -n "$PAGE" ] ; then
|
|
printf '"%s" - %s\n' "$Q" "$A" | $PAGER
|
|
else
|
|
printf '"%s" - %s\n' "$Q" "$A"
|
|
fi
|