#!/usr/bin/env bash

echo "Starting Migration Runner"

# Default MYSQL_DB_PORT
if [ -z "$MYSQL_DB_PORT" ]; then
    MYSQL_DB_PORT=3306
fi

# Default MYSQL_DB_HOST
if [ -z "$MYSQL_DB_HOST" ]; then
    MYSQL_DB_HOST=127.0.0.1
fi

# Wait until the mysql instance we're using is available
timeout 60 bash -c "while ! echo exit | nc -z ${MYSQL_DB_HOST} ${MYSQL_DB_PORT}; do sleep 1; done"

# Run migrations
echo 'Migrating database'
rm -f error_output.log
liquibase \
    --driver=com.mysql.cj.jdbc.Driver \
    --classpath=/var/liquibase/mysql-connector-java-8.0.16/mysql-connector-java-8.0.16.jar \
    --url="jdbc:mysql://${MYSQL_DB_HOST}:${MYSQL_DB_PORT}/${MYSQL_DB_NAME}?autoReconnect=true&useSSL=FALSE" \
    --changeLogFile=db.changelog-master.xml \
    --username="$MYSQL_DEPLOY_USER" \
    --password="$MYSQL_DEPLOY_PASSWORD" \
    update | tee error_output.log

if [[ $(tail -n1 error_output.log) != "Liquibase: Update has been successful." ]]; then
    echo 'Error running migrations. Exiting.'
    exit 1
fi
