#!/bin/bash

set -uo pipefail

patchSQLs=( `git diff --relative --name-only main db/migrations | grep --fixed-strings '.up.sql' | sort` )
if [ ${#patchSQLs[@]} -eq 0 ]; then
    # No patch SQLs to migrate, maybe forgot to run `git add db/migrations` ?
    exit 0
fi
echo "Testing migrations: ${patchSQLs[*]}"

set -e

# apply the db schema in main branch 
mysql -uroot --host 127.0.0.1 -P3306 -e 'drop database if exists _test_infra'
mysql -uroot --host 127.0.0.1 -P3306 -e 'create database _test_infra'
git show main:./db/schema.sql | mysql -uroot --host 127.0.0.1 -P3306 _test_infra

# migrate
if [ "TiDB" = "`scripts/ping_db.sh`" ]; then 
    dsn='mysql://root:@tcp(127.0.0.1:3306)/_test_infra?parseTime=true&tidb_enable_noop_functions=1'
else
    dsn='mysql://root:@tcp(127.0.0.1:3306)/_test_infra?parseTime=true'
fi

currMigration=$(bash ./db/migrations/latest)
migrate -path db/migrations -database "$dsn" force "$currMigration"
migrate -path db/migrations -database "$dsn" up
