1
0
Fork 0
bin/quote-get

51 lines
1.2 KiB
Bash
Executable File

#!/usr/bin/env bash
quotes_cache_file="${HOME}/.cache/quotes.txt";
update_cache_every="1 day";
if [[ "$#" -lt "1" ]]; then
echo -e "Quote generation tool"
echo -e "By Starbeamrainbowlabs"
echo -e ""
echo -e "Downloads and caches a quote file and picks out a random quote."
echo -e ""
echo -e "Usage:"
echo -e " quote-get {quote-file-url}"
exit 1;
fi
quotes_url="$1";
if [ ! -d "$(dirname "${quotes_cache_file}")" ]; then
mkdir -p "${quotes_cache_file}";
fi
function download_quotes {
#echo -ne "> Downloading quotes file - " 1>&2;
curl -o "${quotes_cache_file}" -L ${quotes_url} 2>/dev/null;
#echo -e "done" 1>&2;
}
# Download the quotes file if it doesn't exist already
if [ ! -f "${quotes_cache_file}" ]; then
download_quotes;
fi
# Update the quotes file if it's out of date
oldest_allowed=$(date -d "now - ${update_cache_every}" +%s);
cache_filemtime=$(date -r "${quotes_cache_file}" +%s);
if (( $cache_filemtime <= $oldest_allowed )); then
download_quotes;
fi
# Generate a quote
quote_count=$(cat "${quotes_cache_file}" | wc -l);
# Set the random number generator seed to ensure we give the same quote on a per-day basis
RANDOM=$(date +%Y%m%d);
quote_line=$((( $RANDOM % ${quote_count} )));
sed -n ${quote_line}p "${quotes_cache_file}";