package com.atlassian.bitbucket.mesh.layout;

import com.atlassian.bitbucket.mesh.ApplicationDirs;
import com.atlassian.bitbucket.mesh.io.MoreFiles;

import java.io.IOException;
import java.nio.file.Path;

import static java.util.Objects.requireNonNull;

public class DestroyableStorageLayout extends SimpleStorageLayout {

    private final Path sharedHome;

    public DestroyableStorageLayout(ApplicationDirs applicationDirs, HomeSubdirectoryResolver homeSubdirectoryResolver) {
        super(applicationDirs, homeSubdirectoryResolver);

        sharedHome = requireNonNull(applicationDirs.getSharedHome(), "sharedHome");

        //For the short-term, we need to create a couple Bitbucket Server directories that we previously
        //got from using its DestroyableHomeLayout
        Path configDir = MoreFiles.mkdir(sharedHome, "config");
        Path configGitDir = MoreFiles.mkdir(configDir, "git");
        MoreFiles.mkdir(configGitDir, "hooks");
        MoreFiles.mkdir(configGitDir, "templates");

        Path dataDir = MoreFiles.mkdir(sharedHome, "data");
        MoreFiles.mkdir(dataDir.resolve("git-lfs"), "storage");
        MoreFiles.mkdir(dataDir, "repositories");
    }

    /**
     * Recursively deletes the home directory, effectively deleting all the repositories that were unpacked during
     * testing (as well as any other stray data that might have been created).
     *
     * @throws IOException if the recursive deletion of all files and directories in the home fails
     */
    public void destroy() throws IOException {
        MoreFiles.deleteRecursively(sharedHome);
        MoreFiles.deleteRecursively(getHomeDir());
    }
}
