#!/bin/sh

IFS="
"

TEMP_FILE=$(mktemp)

echo '' | tee -a ${TEMP_FILE}
date +'* %Y-%m-%d' | tee -a ${TEMP_FILE}
echo '' | tee -a ${TEMP_FILE}

for line in $(cat ~/.ledger/commodities.txt ) ; do
    TYPE=$(echo $line | cut -d' ' -f1)
    COMMODITY=$(echo $line | cut -d' ' -f2)
    if [ $TYPE == 'c' ] ; then
        bean-price -e "USD:yahoo/${COMMODITY}USD=X" | sed -e 's/USD=X//' | awk -e '{printf "%s %s %s %.2f %s\n", $1, $2, $3, $4, $5}'  | tee -a ${TEMP_FILE}
    elif [ $TYPE == 's' ] ; then
        ORIGCOMMODITY="$COMMODITY"
        NEWCOMMODITY=$(echo $ORIGCOMMODITY | tr '.' '-')
        bean-price -e "USD:yahoo/$NEWCOMMODITY" | awk -e '{printf "%s %s %s %.2f %s\n", $1, $2, $3, $4, $5}' | sed -e "s/${NEWCOMMODITY}/${ORIGCOMMODITY}/g" | tee -a ${TEMP_FILE}
    elif [ $TYPE == 'm' ] ; then
        bean-price -e "USD:oanda/${COMMODITY}_USD" | sed -e 's/_USD//' | awk -e '{printf "%s %s %s %.2f %s\n", $1, $2, $3, $4, $5}'  | tee -a ${TEMP_FILE}
    elif [ $TYPE == 'f' ] ; then
        bean-price -e "USD:yahoo/${COMMODITY}" | awk -e '{printf "%s %s %s %.2f %s\n", $1, $2, $3, $4, $5}'  | tee -a ${TEMP_FILE}
    else
        echo "$TYPE is not currently a known type."
    fi
done

cat ${TEMP_FILE} >> ~/.ledger/prices.beancount

CWD=$(pwd)
cd ~/.ledger/
git add prices.beancount
git commit -m "Updated beancount price database."
cd ${CWD}
