#!/bin/bash
DIR=`dirname $0`
BRANCH=$1

shopt -s expand_aliases
alias iferr='if [ "$?" != "0" ]; then '

echo -e "BILARA\t: $0 DIR:$DIR"
if [ "$BRANCH" == "" ]; then BRANCH=unpublished; fi
pushd ${DIR}/../local/bilara-data > /dev/null
echo -e "BILARA\t: BRANCH:$BRANCH pwd:"`pwd`

git remote -v | grep "upstream" > /dev/null
RC=$?
if [ "$RC" == "0" ]; then
  echo -e "BILARA\t: upstream remote found (OK)"
elif git remote -v | grep suttacentral > /dev/null; then
  echo -e "BILARA\t: suttacentral remote found (OK)"
else
  echo -e "BILARA\t: adding suttacentral remote"
  git remote add suttacentral https://github.com/suttacentral/bilara-data.git
fi
git fetch
if git checkout $BRANCH >& /dev/null; then
  echo -e "BILARA\t: on $BRANCH branch" 
else
  echo -e "BILARA\t: fetching $BRANCH branch" 
  git checkout --track origin/$BRANCH 
fi

GITLOG_FNAME=.old
if [ -e $GITLOG_FNAME ]; then
  echo -e "BILARA\t: cleaning up $GITLOG_FNAME"
  rm $GITLOG_FNAME
fi

echo -e "BILARA\t: Refreshing sc-voice/$BRANCH ..." 
git pull origin 
iferr echo -e "BILARA\t: git pull origin failed (ERROR)"; exit -1; fi

echo -e "BILARA\t: Refreshing suttacentral/$BRANCH ..."
git fetch suttacentral
iferr echo -e "BILARA\t: fetch suttacentral/$BRANCH (ERROR)"; exit -1; fi
git merge -Xtheirs --no-edit suttacentral/$BRANCH
iferr echo -e "BILARA\t: merge suttacentral/$BRANCH (ERROR)"; exit -1; fi

echo -e "BILARA\t: Committing $BRANCH changes to bilara-data..." 
git commit -am "SuttaCentral Update" 
git push
iferr echo -e "BILARA\t: push suttacentral/$BRANCH (ERROR)"; exit -1; fi

popd
pushd $DIR/..
echo -e "BILARA\t: warming up search"
scripts/js/search.js root of suffering -op

echo -e "BILARA\t: DONE"
