#!/usr/bin/env perl
require 5.008;
use warnings;
use strict;

unshift(@INC, '.');
require qpdf_test_helpers;

chdir("qpdf") or die "chdir testdir failed: $!\n";

require TestDriver;

cleanup();

my $td = new TestDriver('check-encryption');

my @check_encryption_password = (
    # file, password, is-encrypted, requires-password
    ["minimal.pdf", "", 2, 2],
    ["20-pages.pdf", "", 0, 0],
    ["20-pages.pdf", "user", 0, 3],
    );
my $n_tests = 3 * scalar(@check_encryption_password);
foreach my $d (@check_encryption_password)
{
    my ($file, $pass, $is_encrypted, $requires_password) = @$d;
    $td->runtest("is encrypted ($file, pass=$pass)",
                 {$td->COMMAND => "qpdf --is-encrypted --password=$pass $file"},
                 {$td->STRING => "", $td->EXIT_STATUS => $is_encrypted});
    $td->runtest("requires password ($file, pass=$pass)",
                 {$td->COMMAND => "qpdf --requires-password" .
                      " --password=$pass $file"},
                 {$td->STRING => "", $td->EXIT_STATUS => $requires_password});
}

# Exercise reading password from file
open(F, ">args") or die;
print F "user\n";
close(F);
$td->runtest("password from file)",
             {$td->COMMAND => "qpdf --check --password-file=args 20-pages.pdf"},
             {$td->FILE => "20-pages-check.out", $td->EXIT_STATUS => 0},
             $td->NORMALIZE_NEWLINES);
open(F, ">>args") or die;
print F "ignored\n";
close(F);
$td->runtest("ignore extra args from file)",
             {$td->COMMAND => "qpdf --check --password-file=args 20-pages.pdf"},
             {$td->FILE => "20-pages-check-password-warning.out",
                  $td->EXIT_STATUS => 0},
             $td->NORMALIZE_NEWLINES);
unlink "args";
$td->runtest("password from stdin)",
             {$td->COMMAND => "echo user |" .
                  " qpdf --check --password-file=- 20-pages.pdf"},
             {$td->FILE => "20-pages-check.out", $td->EXIT_STATUS => 0},
             $td->NORMALIZE_NEWLINES);

cleanup();
$td->report($n_tests);
