package crypto.r35157.nenjim;

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

public class DockerSwarmSecrets implements ImmutableProperties {
    public DockerSwarmSecrets() {
        refresh();
    }

    @Override
    public String getProperty(String key) throws IOException {
        Path dir = Paths.get(BASE_DIR);

        if(!Files.exists(dir)) {
            throw new IOException(ERROR_DIR_PREFIX + "do not exist!");
        }

        if(!Files.isDirectory(dir)) {
            throw new IOException(ERROR_DIR_PREFIX + "is not a directory!");
        }

        if(!Files.isReadable(dir)) {
            throw new IOException(ERROR_DIR_PREFIX + "is not readable!");
        }

        Path file = Paths.get(BASE_DIR, key);

        if(!Files.exists(file)) {
            throw new IOException(ERROR_FILE_PREFIX + file + "' do not exist!");
        }

        if(Files.isDirectory(file)) {
            throw new IOException(ERROR_FILE_PREFIX + file + "' is not a file!");
        }

        if(!Files.isReadable(file)) {
            throw new IOException(ERROR_FILE_PREFIX + file + "' is not readable!");
        }

        String value = Files.readString(file).trim();
        return value;
    }

    @Override
    public void refresh() {}

    @Override
    public int getSize() {
        return -1;
    }

    private static final String BASE_DIR = "/run/secrets/";
    private static final String ERROR_DIR_PREFIX = "Docker Swarm Secrets directory '" + BASE_DIR + "' ";
    private static final String ERROR_FILE_PREFIX = "Docker Swarm Secrets file '";
}
