#!/usr/bin/env perl

# Some tests for the --set-scripts-executable option.

use lib 'lib/perl';
use Test::More 'no_plan';
use Test::Darcs;
use Shell::Command;
use strict;
use Cwd 'abs_path';

my $test_dir = abs_path();

if ($^O =~ /msys/i) {
    pass 'test does not work on windows';
} else {
    my $test_name = 'darcs pull --set-scripts-executable works';

    use File::Temp 'tempdir';
    chdir tempdir( CLEANUP => 1 );

    mkpath 'temp1';
    chdir 'temp1';
    darcs 'init';

    cp "$test_dir/".__FILE__, 'script.pl' || die $!;
    chmod 0644, 'script.pl' || die $!;
    system 'date > nonscript';
    ok( (-r 'script.pl'), 'pre test: script exists and is readable' );
    ok( ! (-x 'script.pl'), 'pre test: script is not executable' );
    ok( (-r 'nonscript'), 'pre test: nonscript exists and is readable' );
    ok( ! (-x 'nonscript'), 'pre test: nonscript is not executable' );

    darcs  'add script.pl nonscript';
    like( ( darcs qw!record --patch-name 'uno' --all ! ), qr/finished recording/i );
    ok( chdir '..');
    # sans --set-scripts-executable (should not be executable)
    mkpath 'temp2';
    chdir 'temp2';
    darcs 'init';
    like( ( darcs qw%pull -a ../temp1 %) , qr/finished pulling/i );
    ok( (-r 'script.pl'), 'reality check: file has been pulled and is readable' );
    ok( (-r 'nonscript'), 'reality check: other file has been pulled and is readable' );

    ok(! (-x 'script.pl'), "nothing should be executable");
    ok(! (-x 'nonscript'), "nothing should be executable" );
    chdir '..';

    # darcs pull --set-scripts-executable
    cleanup 'temp2';
    mkpath 'temp2';
    chdir 'temp2';
    darcs 'init';
    like( ( darcs qw%pull --set-scripts-executable -a ../temp1 %) ,
           qr/finished pulling/i );
    ok( (-r 'script.pl'), 'reality check: file has been pulled and is readable' );
    ok( (-r 'nonscript'), 'reality check: other file has been pulled and is readable' );

    ok( (-x 'script.pl'), $test_name );
    ok(! (-x 'nonscript'), "innocent bystanders aren't set to be executable" );
    chdir '../';     # now outside of any repo

    # now let's try the same thing with get
    `rm -rf temp2`;
    like( darcs('get --set-scripts-executable temp1 temp2') ,
           qr/finished/i );
    chdir 'temp2';
    ok( (-r 'script.pl'), 'reality check: file has been gotten and is readable' );
    ok( (-r 'nonscript'), 'reality check: other file has been gotten and is readable' );

    ok( (-x 'script.pl'), $test_name );
    ok(! (-x 'nonscript'), "innocent bystanders aren't set to be executable" );
}
