/*-
 * ~~~~~~licensing~~~~~~
 * liquibase-updater
 * ==========
 * Copyright (C) 2020 - 2021 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.esb.platform.runtime.core.initializer.storage.initializer.liquibase.updater;

import liquibase.Contexts;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.osgi.OSGiResourceAccessor;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;

import javax.sql.DataSource;

public class LiquibaseUpdater {

	private static final Logger log = LoggerFactory.getLogger(LiquibaseUpdater.class);
	
    private static final String CHANGELOG_PATH = "db/changelog.xml";

    public LiquibaseUpdater(DataSource dataSource, BundleContext bundleContext) {
    	java.sql.Connection connection = null;
        try {
            connection = dataSource.getConnection();

            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
            String config = bundleContext.getBundle().getEntry(CHANGELOG_PATH).getPath();

            Liquibase liquibase = new liquibase.Liquibase(config,
                    new OSGiResourceAccessor(bundleContext.getBundle()), database);

            liquibase.update(new Contexts());
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
			if (connection != null)
				try {
					connection.close();
				} catch (SQLException e) {
					log.error("LiquibaseUpdater", e);
				}
		}
    }
}
