#!/bin/bash

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

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

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

cat \
  $SCRIPTDIR/revert_00009_backup.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00012_add_qna_users_ds.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00013_add_priority.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00014_add_attr_json.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00015_add_created_at.sql \
  $SCRIPTDIR/../../../infra/annotator_db/service/migrations/00016_add_chum_uri.sql \
  $SCRIPTDIR/backfill_qna_rater_manager_date.sql \
  $SCRIPTDIR/backfill_qna_priority.sql \
  $SCRIPTDIR/final_commit.sql \
  | PGPASSWORD=Rohj2AhtCai6ioriEech5naiic3ud7Xa 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
