#!/usr/bin/env bash

set -e

curl_opts=(--silent --connect-timeout 1 --no-progress-meter -X GET)

curl_cbr () {
  local today=$(date +%d/%m/%Y)
  local start_range=$(date +%d/%m/%Y -d '-14 day')
  local usd=R01235

  curl ${curl_opts[@]} "https://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=$start_range&date_req2=$today&VAL_NM_RQ=$usd" | \
    sed -e "s/<[A-Z]/\n\0/g" | \
    grep Value | \
    sed -e "s#<\/\?\w\+>##g" | \
    sed -e "s/,/./g"
}

curl_exchangerate () {
  local start_date=$(date +%Y-%m-%d -d '-1 day')
  local end_date=$(date +%Y-%m-%d)

  curl ${curl_opts[@]} "https://api.exchangerate.host/timeseries?start_date=$start_date&end_date=$end_date&base=USD&symbols=RUB&places=4&format=xml"  | \
    sed -e "s/<[a-z]/\n\0/g" | \
    grep rate | \
    sed -e "s#<\/\?\w\+>##g"
}

res=($(curl_cbr))
if [ -z "$res" ]; then
  text="NO DATA"
  echo "%{F@error@}${text}%{F-}"
  exit 0
fi

diff=$(echo ${res[-1]} ${res[-2]} | awk '{ print $1 - $2 }')
arror="↑"
color='@success@'
if [ ${diff:0:1} == '-' ]; then
  diff=${diff:1}
  arror="↓"
  color='@error@'
fi

echo "${res[-1]} (%{F${color}}${arror}%{O3}${diff}%{F-})"
exit 0

