#!/usr/bin/env perl
# AP-Client: CLI-based client / toolbox for ActivityPub
# Copyright © 2020-2021 AP-Client Authors <https://hacktivis.me/git/ap-client/>
# SPDX-License-Identifier: BSD-3-Clause
use strict;
use utf8;
no warnings; # Wide Character…

use Getopt::Std;

use LWP::UserAgent;
use HTTP::Request::Common;

my %options=();
my $ua = LWP::UserAgent->new;


getopts("rju:", \%options);

if($#ARGV != 0) {
	print "usage: ap-fetch.pl [-r|-j|-u user:pass] <url>\n";
	print " -j  Pipe into jq(1)\n";
	print " -r  Raw output\n";
	print " -u user:pass  HTTP Basic Auth credentials\n";
	print "By default, when -j and -r are absent it pipes the data into ap-represent.pl.\n";
	exit 1;
}

$ua->agent("AP-Client fetch <https://hacktivis.me/git/ap-client/>");
my $req = HTTP::Request->new(GET => $ARGV[0]);
$req->header('Accept' => 'application/activity+json');

if(defined $options{u}) {
	my ($user, $password) = split(/:/, $options{u});
	$req->authorization_basic($user, $password);
}

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

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 {
			open(my $pipe_out, '|-', 'ap-represent.pl') or die "Couldn't open a pipe into ap-represent.pl: $!";
			print $pipe_out $res->content;
		}
	} else {
		print "Got $content_type instead of $content_match";
	}
} else {
	print "Got ", $res->status_line, " instead of 2xx\n";
}
