### ----------------------------------------------------
### -- Archive::Libarchive
### -- Licenses: Artistic-2.0
### -- Authors: Fernando Santagata
### -- File: t/02-read.rakutest
### ----------------------------------------------------
#!/usr/bin/env raku

use Test;
use lib 'lib';
use Archive::Libarchive;
use Archive::Libarchive::Constants;

constant AUTHOR = ?%*ENV<TEST_AUTHOR>;

my Archive::Libarchive $a .= new: operation => LibarchiveRead;
is $a.WHAT, Archive::Libarchive, 'Create object for reading';
throws-like
  { $a.open: 'notafile' },
  X::Libarchive,
  message => /'File not found'/,
  'Open file fails';
my $path = $*PROGRAM-NAME.subst(/ <-[/]>+$/, '');
lives-ok { $a.open: $path ~ 'test.tar.gz' }, 'Open file succeedes';
my Archive::Libarchive::Entry $e .= new;
is $a.next-header($e), True, 'Read first entry from file';
is $e.pathname, 'test1', 'Entry pathname';
is $e.filetype, AE_IFREG, 'Entry filetype';
ok is-file($e.filetype), 'check file type';
is-deeply $e.filetype(:decode), [True, False, False, False, False, False, False], 'decoded file type as array';
is $e.perm, 0o644, 'Entry permission bits';
is $e.mode, 0o100644, 'Entry mode'; # AE_IFREG + 0o644
is $e.uid, 1000, 'Entry uid';
is $e.gid, 1000, 'Entry gid';
if AUTHOR {
  is $e.uname, 'nando', 'Entry uid as text';
  is $e.gname, 'nando', 'Entry gid as text';
}else{
  skip 'Skipping author test';
}
lives-ok { $a.data-skip }, 'Skip file data';
my $buffer = slurp $path ~ 'test.tar.gz', :bin;
my $am = Archive::Libarchive.new: operation => LibarchiveRead, file => $buffer;
is $am.WHAT, Archive::Libarchive, 'Create object for reading from memory';
is $am.next-header($e), True, 'Read first entry from memory';
is $e.pathname, 'test1', 'Entry pathname from memory';
lives-ok { $am.close }, 'Close archive';
my Archive::Libarchive $a1 .= new: operation => LibarchiveRead, file => 't/test.tar.gz';
my Archive::Libarchive::Entry $e1 .= new;
my $content;
while $a1.next-header: $e1 {
  if $e1.pathname eq 'test3' {
    $content = $a1.read-file-content: $e1;
  }
}
is $content.decode('utf-8'), "test3\n", 'Read file content';
done-testing;


