#!/usr/bin/env perl
# CVE-Client: CLI-based client / toolbox for CVE.org
# Copyright © 2021-2023 CVE-Client Authors <https://hacktivis.me/git/cve-client/>
# SPDX-License-Identifier: AGPL-3.0-only
our $VERSION = 'v1.0.5';
use strict;
use utf8;
no warnings;    # Wide Character…

use App::CveClient qw(print_cve);

use Getopt::Std;
$Getopt::Std::STANDARD_HELP_VERSION = 1;
use LWP::UserAgent;
use JSON::MaybeXS;

=head1 NAME

cve-client - CLI-based client / toolbox for CVE.org

=head1 SYNOPSIS

B<cve-client> [-r|-j|-g] <CVE-IDs ...>

=head1 DESCRIPTION

B<cve-client> fetches CVE-IDs from CVE.org API and write the result to standard output.

By default it is pretty-printed into a plain-text format.

=over 3

=item -j

Pipe into jq(1)

=item -r

Raw output, print server's output without any decoding

=item -g

Pretty-print but compatible with Gemini.

=back

=head1 LICENSE

AGPL-3.0-only

=cut

my $json = JSON::MaybeXS->new(utf8 => 1);

my %options = ();

sub HELP_MESSAGE {
	print "usage: cve-client [-r|-j|-g] <CVE-IDs ...>\n";
	print " -r  Raw output\n";
	print " -j  Pipe into jq(1)\n";
	print " -g  Gemtext format\n";
	print "Otherwise it tries to do a plain-text representation.\n";
	exit 1;
}

sub fetch_cve {
	my ($cve_id) = @_;
	my $url = 'https://www.cve.org/api/?action=getCveById&cveId=' . $cve_id;

	#print "Fetching: ", $url, "\n";
	my $ua = LWP::UserAgent->new;
	$ua->agent("CVE-Client fetch <https://hacktivis.me/git/cve-client/>");
	my $req = HTTP::Request->new(GET => $url);

	#$req->header('Accept' => 'application/json');

	my $res = $ua->request($req);

	my $format = $options{g} ? 'gemini' : 'plain';

	if ($res->is_success) {
		my $content_type  = $res->header("Content-Type");
		my $content_match = 'application/json';

		if ($content_type == $content_match) {
			if (defined $options{r}) {
				print $res->content;
			} elsif (defined $options{j}) {
				open(my $pipe_out, '|-', 'jq .')
				  or die "Couldn't open a pipe into jq: $!";
				print $pipe_out $res->content;
			} else {
				my $object = $json->decode($res->content);
				print_cve($object, $cve_id, $format);
			}
		} else {
			print "Got $content_type instead of $content_match";
		}
	} else {
		print "Got ", $res->status_line, " instead of 2xx\n";
	}
}

getopts("rjg", \%options);

if ($#ARGV < 0) {
	HELP_MESSAGE;
	exit 1;
}

for (@ARGV) {
	fetch_cve($_) if $_ =~ /^CVE-[0-9]{4}-[0-9]{4,19}$/;
}
