#!/bin/bash
set -e

DB_ENVIRONMENT=$1
if [ -z $DB_ENVIRONMENT ] ; then
    DB_ENVIRONMENT="default"
fi

source env/$DB_ENVIRONMENT.conf

# Create the control table, if it doesn't exist
cat <<-EOF | psql $PSQL_OPTS -d $DB_NAME
BEGIN;
CREATE TABLE IF NOT EXISTS database_versions (
  version varchar(32) not null,
  is_active boolean not null default false,
  creation_date timestamp not null default current_timestamp
);
END;
EOF

function add-version() {
  psql $PSQL_OPTS -c "update database_versions set is_active = false where is_active = true" $DB_NAME
  psql $PSQL_OPTS -c "insert into database_versions (version, is_active) values ('$1', TRUE)" $DB_NAME
}

current_version=$(psql $PSQL_OPTS -Atc "select version from database_versions where is_active = true" $DB_NAME)

for f in $(ls -1 migrations/*.sql | sort); do
  filev=$(basename $f .sql)
  if [[ $filev > $current_version ]]; then
    psql $PSQL_OPTS -vON_ERROR_STOP= -1f $f $DB_NAME
    # No need to check return code because of the 'set -e'
    add-version $filev
  fi
done
