package com.atlassian.bitbucket.mesh;

import com.atlassian.bitbucket.mesh.layout.StorageLayout;
import org.h2.mvstore.MVStoreTool;

import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;

public class H2DatabaseValidator {

    private final StorageLayout storageLayout;

    public H2DatabaseValidator(StorageLayout storageLayout) {
        this.storageLayout = storageLayout;
    }

    public void validate() {
        Path dbFile = storageLayout.getHomeDir().resolve("mesh.mv.db");

        if (Files.exists(dbFile) && !isSupportedFormat(dbFile)) {
            throw new UnsupportedH2StoreException("The storage format for the internal database that you are using has changed and requires manual migration.", getAction());
        }
    }

    private static boolean isSupportedFormat(Path filePath) {
        return MVStoreTool.info(filePath.toString(), new StringWriter()) == null;
    }

    private String getAction() {
        return "Please perform the manual migration of the database. See https://confluence.atlassian.com/bitbucketserver088/migrate-h2-database-1216583295.html.";
    }
}