#!/usr/bin/env perl

# Issue595
#
# A test for running "darcs get" when the parent directory has restrictive
# permissions.  The bug is that darcs trys to "chdir" to the current directory
# using the full path.  The permissions on the parent directory prevent this
# from working, even though the current repo and the remote have sufficient
# permissions. 
#
# The real-world case where this would happen would be a web-server with
# restrictive permissions on "/home", with a user running darcs within that. 

# Also find the right path from the bugs directory. 
use lib ('lib/perl', '../tests/lib/perl');
use Test::More 'no_plan';
use Test::Darcs;
use Shell::Command;
use strict;
use warnings;

# Start in a randomly named temporary directory that deletes itself when we're done. 
use File::Temp 'tempdir';
chdir tempdir( CLEANUP => 1 );

use Cwd 'realpath';

if ($^O =~ /win/i or $^O =~ /msys/i) {
    pass 'test does not work on windows';
} else {
# Set up a "remote" repo
# and a directory with restrictive permissions with
ok(mkpath('tmp_remote'), "tmp_remote created");
ok(mkpath('tmp_restrictive/liberal'), "tmp_restrictive/liberal created");

ok(chdir('tmp_remote'), "chdir tmp_remote");
darcs 'init';

ok( chdir('../tmp_restrictive/liberal'), "chdir to liberal") || die;;


# Get the path just above these repos;
my $top_path = realpath();
$top_path =~ s?tmp_restrictive/liberal??;
my $remote_full_path = "$top_path/tmp_remote";

ok(chmod('0111', '../../tmp_restrictive'), 'chmod 0111 of tmp_restrictive');

ok( chdir('../..'), 'can cd out of our darcs repository');

ok( chdir('tmp_restrictive/liberal'), 'can cd back into our darcs repository');

if (realpath() =~ qr/tmp_restrictive.liberal/) {

  my $out = darcs "get $remote_full_path";
  unlike($out, qr/permission denied/i, "Avoid permission denied error");

} else {

  local $TODO = 'it seems that solaris does not allow CD into directory?';
  ok(0,"Can't do restrictive_upstream_permissions.pl on this platform.");

}

ok(chdir("$top_path"), "chdir $top_path");
# We have to fix the permissions, just so we can delete it.
ok(chmod('0755', 'tmp_restrictive'), 'chmod 0755 of tmp_restrictive');
}
