package DX::Lib::FS::Action::CreateFile;

use aliased 'DX::Lib::FS::Fact::PathStatus';
use aliased 'DX::Lib::FS::Fact::PathStatusInfo';
use POSIX ();
use Moo;

with 'DX::Role::Action';

has path => (is => 'ro', required => 1);

has mode => (is => 'ro', predicate => 1);

sub expected_effect {
  my ($self) = @_;
  return +(path_status => PathStatus->new(
    path => $self->path,
    info => PathStatusInfo->new(
      is_file => 1,
      mode => ($self->has_mode ? $self->mode : '')
    )
  ));
}

sub _do_run {
  my ($self) = @_;
  if ($self->has_mode) {
    my $umask = umask(0000);
    my $fd = POSIX::open(
      $self->path, POSIX::O_CREAT | POSIX::O_RDONLY, oct($self->mode)
    ) or do { umask($umask); die "Couldn't create ${\$self->path}: $!" };
    POSIX::close($fd);
    umask($umask);
  } else {
    open my $fh, '>>', $self->path or die "Couldn't create ${\$self->path}: $!";
  }
  +(path_status => PathStatus->new(path => $self->path));
}

1;
