package NGCP::Service::IO;

use strict;
use warnings;

use Exporter qw(import);
use NGCP::Log::Functions;
use File::Spec::Functions qw(catfile canonpath);
use IPC::Cmd qw(run);

our $VERSION = '0.01';
our @EXPORT = qw(
    get_root_dir
    execute
);

sub get_root_dir
{
    return $ENV{NGCP_ROOT_DIR} // '';
}

sub execute
{
    my ($cmd, %opts) = @_;
    my $root_dir = get_root_dir();

    if (length $root_dir) {
        $cmd->[0] = canonpath(catfile($root_dir, $cmd->[0]));
        debug("append NGCP_ROOT_DIR: $cmd->[0]");
    }

    debug("execute: @{$cmd}");

    my ($ok, $err, undef, $stdout, $stderr) = run(command => $cmd);
    my $rc = $ok ? 0 : 1;

    debug("execute exit code = $rc");

    # IPC::Cmd error handling sucks...
    die $err if not $ok and $err =~ m/No such file or directory/;

    if ($opts{verbose}) {
        print { \*STDOUT } "@{$stdout}";
        print { \*STDERR } "@{$stderr}";
    }

    return ($rc, $stdout, $stderr) if wantarray;
    return $rc;
}

1;
