#!/bin/sh

# Shows the price for desired cryptocurrencies. Module updates automatically
# every calendar day, but can also be updated with a middle click.

# Currencies should be ;-separated:
# human-readable name;urlname;icon
coins="Bitcoin;btc;2|
Ethereum;eth;|3|
"

# Directory where currency info is stored.
dir="${XDG_DATA_HOME:-$HOME/.local/share}/crypto-prices"

getprices() { # The command to get the desired prices
	printprices
	{ rm -rf "${dir:?}/*"
	echo "$coins" | while IFS=';' read -r human web icon; do
		val="$(curl -s "rate.sx/1$web")" && [ ! -z "$web" ] &&
		echo "$icon;$val;$human" > "$dir/$web"
	done; [ -d "$dir" ] && touch "$dir"
	pkill -RTMIN+6 "${STATUSBAR:-dwmblocks}" ;} &
	exit
	}

printprices() { # Print/format all prices
	for x in "$dir"/*; do
		[ -f "$x" ] || break
		info="$(cut -d';' -f-2 --output-delimiter '' "$x")"
		printf "%s$" "${info:0:10}"
	done | sed 's/ $/\n/'
	}

[ ! -d "$dir" ] && mkdir -p "$dir" && { getprices; exit ;}

# If currencies haven't been updated today, try to update them.
[ -z "$(find "$HOME/.local/share/crypto-prices" -mmin -5)" ] &&
	{ ping -q -c 1 example.org >/dev/null 2>&1 && getprices ;} || printprices

case $BLOCK_BUTTON in
	1) "$TERMINAL" -e "cointop" "$1" ;;
	2) getprices ;;
esac
