#!/bin/bash

set -e # exits if a command fails
set -u # errors if an variable is referenced before being set

if [ $# != 2 ]; then
    echo "please enter db host/password"
    exit 1
fi

export DBHOST=$1
export DBPASSWD=$2
SCRIPTDIR=$(dirname $(readlink -f $0))

cat \
  $SCRIPTDIR/event_bank_modifying_qna_table.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00017_add_3_new_tables.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00018_add_mining_columns.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00019_add_event_table.sql \
  $SCRIPTDIR/final_commit.sql \
  | PGPASSWORD=$DBPASSWD psql \
  -X \
  -h $DBHOST \
  -U qna \
  -p 5432 \
  --echo-all \
  --set AUTOCOMMIT=off \
  --set ON_ERROR_STOP=on

psql_exit_status=$?

if [ $psql_exit_status != 0 ]; then
    echo "psql failed while trying to run sql scripts" 1>&2
    exit $psql_exit_status
fi

echo "Job Done. Success!"
exit 0
