package com.atlassian.stash.internal.util;

import com.google.common.collect.Sets;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;

public class FilePermissionUtilsTest {

    @Test
    public void restrictFilePosix() throws Exception {
        assumeFalse(SystemUtils.IS_OS_WINDOWS);
        HashSet<PosixFilePermission> restrictedPermissions = Sets.newHashSet(
                PosixFilePermission.OWNER_WRITE,
                PosixFilePermission.OWNER_READ,
                PosixFilePermission.GROUP_READ);
        File file = File.createTempFile("restriction", "test");
        assertNotEquals(Files.getPosixFilePermissions(file.toPath()), restrictedPermissions);

        FilePermissionUtils.setRestrictedFilePermissions(file);

        assertEquals(Files.getPosixFilePermissions(file.toPath()), restrictedPermissions);

        file.delete();
    }

    @Test
    public void restrictFileWindows() throws Exception {
        assumeTrue(SystemUtils.IS_OS_WINDOWS);
        File file = File.createTempFile("restriction", "test");

        FilePermissionUtils.setRestrictedFilePermissions(file);

        AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file.toPath(),
                AclFileAttributeView.class);
        assertThat(fileAttributeView.getAcl().size(), is(2));
        assertEquals(fileAttributeView.getAcl().get(0).permissions(), FilePermissionUtils.ACL_ENTRY_PERMISSIONS);

        file.delete();
    }
}