#!/bin/bash

# Stop on first non-zero exit code
set -e

if [ `whoami` != 'jenkins' ]; then
    echo "This test is designed to be executed from Jenkins CI."
    echo "Do not run this without updating paramters.yml database name."
    exit 1
fi

pushd /opt/irontec/ivozprovider/schema
    # Create database and load initial data
    bin/console doctrine:database:drop --force || true
    bin/console doctrine:database:create -vv
    mysql -uroot -hdata.ivozprovider.local ivozprovider < initial.sql

    # Apply all migrations
    bin/console doctrine:migrations:migrate -vv --no-interaction

    # Validate ORM mapping files
    bin/console doctrine:schema:validate -vv

    # Check no changes are pending to be mapped
    bin/console doctrine:schema:update -vv --dump-sql | grep 'Nothing to update'

    # Check no changes are generated
    bin/console doctrine:migrations:diff --allow-empty-diff -n | grep 'No changes detected'

    # Ensure all migrations extends from LoggableMigration
    INCORRECT_MIGRATIONS=$(grep -R "final class Version" DoctrineMigrations | grep -v LoggableMigration | wc -l)
    if [ $INCORRECT_MIGRATIONS -gt 0 ]; then
        echo "Following migrations does not extend from LoggableMigration:"
        grep -R "final class Version" DoctrineMigrations | grep -v LoggableMigration | cut -d":" -f1
        exit 1
    fi
popd

