package com.atlassian.bitbucket.mesh.repository;

import com.atlassian.bitbucket.mesh.git.hook.GitHookService;
import com.atlassian.bitbucket.mesh.io.MoreFiles;

import javax.annotation.Nonnull;
import java.nio.file.Path;
import java.time.Instant;

import static java.util.Objects.requireNonNull;

/**
 * A storage shard denoting the Bitbucket Data Center/Server shared home.
 * <p>
 * Prior to Bitbucket Data Center 6.0, the shared home was the only place to store repository data. As a result, on
 * most instances (be they Data Center or Server), this shard holds the majority of repositories.
 */
class SharedHomeBitbucketServerShard extends BitbucketServerShard {

    static final String ID = "0";

    private final Path hooksDir;
    private final Path lfsStorageDir;
    private final Path repositoriesDir;
    private final Path templateDir;

    SharedHomeBitbucketServerShard(@Nonnull Path sharedHomeDir, @Nonnull Path workTreesDir) {
        super(ID, sharedHomeDir, workTreesDir);

        Path dataDir = sharedHomeDir.resolve("data");
        lfsStorageDir = MoreFiles.mkdir(dataDir.resolve("git-lfs").resolve("storage"));
        repositoriesDir = dataDir.resolve("repositories");

        Path gitConfigDir = MoreFiles.resolve(sharedHomeDir, "config", "git");
        //This is the same subpath as the hooksDir in a legacy data store, but uses a different root directory
        hooksDir = gitConfigDir.resolve("hooks");
        templateDir = gitConfigDir.resolve("templates");
    }

    @Nonnull
    @Override
    Path getHooksDir() {
        return hooksDir;
    }

    @Nonnull
    @Override
    String getLayoutTar() {
        return "/templates/dc-sharedhome-datastore.tar";
    }

    @Nonnull
    @Override
    Path getLfsDir(@Nonnull String hierarchyId) {
        return lfsStorageDir.resolve(requireNonNull(hierarchyId, "hierarchyId"));
    }

    @Nonnull
    @Override
    Path getRepositoriesDir(@Nonnull String hierarchyId) {
        return repositoriesDir;
    }

    @Nonnull
    @Override
    Path getTemplateDir() {
        return templateDir;
    }

    @Override
    void start(@Nonnull GitHookService hookService) {
        Instant start = Instant.now();

        super.start(hookService);

        pruneStaleConfig(start, templateDir);
    }
}
