#!/usr/bin/perl

use strict;
use Debian::PkgJs::Utils;
use Debian::PkgJs::Version;
use JSON;
use Pod::Usage;
use Pod::Text;

my $cmd = shift @ARGV;

pod2usage(
    -message => 'Missing command',
    -exitval => 1,
) unless $cmd;

pod2usage(
    -message => 'Bad command',
    -exitval => 2,
  )
  unless $cmd =~
  /^(?:components_list|modules_list|pjson|main|-(?:h|v|-help|-version))$/;

our $obj = bless {}, 'Debian::PkgJs::Utils';

use constant _sub => {
    '-v' => sub {
        return $VERSION;
    },
    '-h' => sub {
        return pod2usage( -verbose => 2 );
    },
    main => sub {
        return $obj->pjson( $obj->main_package );
    },
    components_list => sub {
        my $res = $obj->component_list;
        return join( '', map { "$_\n" } sort keys %$res );
    },
    modules_list => sub {
        my $res = $obj->component_list;
        return
          join( '', map { $obj->pjson($_)->{name} . "\n" } sort keys %$res );
    },
    pjson => sub {
        my $cmp = shift(@ARGV) || '.';
        my $res = $obj->pjson($cmp);
        while ( $_ = shift @ARGV ) {
            if ( ref $res ) {
                if ( defined $res->{$_} ) {
                    $res = $res->{$_};
                }
                else {
                    die "Unable to find $_ in $cmp/package.json" if (@ARGV);
                    $res = '';
                }
            }
            else {
                pod2usage(
                    -message => 'Bad json path',
                    -exitval => 3,
                );
            }
        }
        my $ref = ref($res) || '';
        return
            $ref eq 'HASH'  ? JSON::to_json($res)
          : $ref eq 'ARRAY' ? join( "\n", @$res )
          :                   $res;
    },
    main => sub {
        return $obj->pjson('.')->{name};
    },
};

_sub->{'--version'} = _sub->{'-v'};
_sub->{'--help'}    = _sub->{'-h'};

my $res = _sub->{$cmd}->();
chomp $res;
print $res. ( $res =~ /./ ? "\n" : '' );
__END__
=head1 NAME

pkgjs-utils - Nodejs package utilities

=head1 SYNOPSIS

  $ pkgjs-utils main
  $ pkgjs-utils components_list
  $ pkgjs-utils modules_list
  $ pkgjs-utils pjson .
  $ pkgjs-utils pjson packages/jest-diff
  $ pkgjs-utils pjson packages/jest-diff version
  $ pkgjs-utils pjson . scripts test
  $ pkgjs-utils pjson packages/jest-diff scripts test

=head1 DESCRIPTION

Collection of little commands to read <component>/package.json overridden by
debian/nodejs/<component>/* files.

=head1 AUTHOR

Yadd <yadd@debian.org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2021 by Yadd <yadd@debian.org>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
.
On Debian systems, the complete text of version 2 of the GNU General
Public License can be found in `/usr/share/common-licenses/GPL-2'

=cut
