package com.atlassian.bitbucket.mesh.repository;

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

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

import static java.util.Objects.requireNonNull;

/**
 * A storage shard denoting a legacy Bitbucket Data Center {@code DataStore}.
 * <p>
 * {@code DataStore}s were added in Bitbucket Data Center 6.0 as a way to provide multiple NFS mounts rather than
 * using a single massive shared home. They were similar, in some ways, to Mesh's {@link DataStore} concept, but
 * used a different storage layout.
 */
class AdditionalBitbucketServerShard extends BitbucketServerShard {

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

    AdditionalBitbucketServerShard(@Nonnull String id, @Nonnull Path rootDir, @Nonnull Path templateDir,
                                   @Nonnull Path workTreesDir) {
        super(id, rootDir, workTreesDir);

        this.templateDir = requireNonNull(templateDir, "templateDir");

        repositoriesDir = rootDir.resolve("repositories");
        //This is the same subpath as the hooksDir in the shared home, but uses a different root directory
        hooksDir = MoreFiles.resolve(repositoriesDir, "config", "git", "hooks");
    }

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

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

    @Nonnull
    @Override
    Path getLfsDir(@Nonnull String hierarchyId) {
        return getHierarchyDir(hierarchyId).resolve("lfs");
    }

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

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

    private Path getHierarchyDir(String hierarchyId) {
        return repositoriesDir.resolve(requireNonNull(hierarchyId, "hierarchyId").substring(0, 2))
                .resolve(hierarchyId.substring(2));
    }
}
