use strict;

use Test::More 1;
END{ done_testing() unless caller }

use Config;
use File::Temp qw(tempdir);

sub is_cygwin () { scalar grep { lc($^O) eq $_ or lc($Config{osname}) eq $_ } qw( cygwin ) }

sub is_msys   () { scalar grep { lc($^O) eq $_ or lc($Config{osname}) eq $_ } qw( msys msys2 ) }

sub is_win32  () { $^O eq 'MSWin32' }

sub is_unix_superuser () {
    ( not is_win32() and ( $> == 0 or $< == 0 ) )
    or
    ( is_cygwin() and grep { $_ == 544 } split /\s+/, `/usr/bin/id -G` )
	}

my $dir = tempdir( CLEANUP => 0 ) or BAIL_OUT( "Could not setup temp directory" );
print "Temp dir in <$dir>\n";

unless( -d $dir ) {
	mkdir 'test_files', 0700
		or BAIL_OUT( "Could not make directory! $!" );
	}

chdir $dir or BAIL_OUT( "Could not change directory! $!" );

my @files = qw(
max_file       non_zero_file  not_readable   readable       zero_file
executable     min_file       not_executable not_writable   writable
mtime_file
);

foreach my $file ( @files ) {
	open FH, "> $file";
	close FH;
	}

{
my $count = chmod 0644, @files;
is( $count, scalar @files ) or BAIL_OUT( "Could not make files readable" );
}

{
my $count = chmod 0400, 'readable', 'not_writable', 'not_executable';
is( $count, 3 ) or BAIL_OUT( "Could not make files readable" );
}

{
my $count = chmod 0200, 'writable', 'not_readable',
		'zero_file', 'max_file', 'non_zero_file';
is( $count, 5 ) or BAIL_OUT( "Could not make files writable" );
if( is_win32() ) {
	system 'attrib', '+', 'not_readable';
	}
}

{
my $count = chmod 0100, 'executable';
is( $count, 1 ) or BAIL_OUT( "Could not make files executable" );
}

truncate 'zero_file', 0;
truncate 'max_file', 10;
truncate 'min_file',  0;

{
open FH, '> min_file' or BAIL_OUT( "Could not write to min_file: $!" );
binmode FH; #, Windows, yo!
print FH 'x' x 40, $/, 'x' x 11, $/;
close FH;
}
is( -s 'min_file', 51 + 2 * length( $/ ) );

mkdir 'sub_dir', 0755 or BAIL_OUT( "Could not cerate subdir: $!" );