use JSON;
use LWP::Simple;

use strict;
use warnings;

my $pages = 1;
my $page = 1;

my @extensions;

mkdir $_ foreach qw/pages files unpacked/;

while ($page <= $pages) {
	warn "=== Page $page ===";

	my $name = "pages/$page.json";
	getstore ("https://extensions.gnome.org/extension-query/?page=$page&shell_version=all", $name)
		unless -f $name;
	open (my $file, '<', $name);
	my $json = decode_json (join '', <$file>);
	die unless $json;
	$pages = $json->{numpages};
	$page++;
	#push @extensions, @{$json->{extensions}};

	foreach my $extension (@{$json->{extensions}}) {
		next unless %{$extension->{shell_version_map}};

		my ($newest) = reverse
			sort { $a->{version} <=> $b->{version} }
			values %{$extension->{shell_version_map}};

		my $dir = sprintf 'unpacked/%s.v%s', $extension->{uuid}, $newest->{version};
		-d $dir and next;

		my $name = sprintf 'files/%s.v%s.shell-extension.zip', $extension->{uuid}, $newest->{version};
		my $uri = sprintf 'https://extensions.gnome.org/download-extension/%s.shell-extension.zip?version_tag=%s',
			$extension->{uuid}, $newest->{pk};

		warn $uri;
		getstore ($uri, $name) unless -f $name;

		mkdir $dir;
		system "unzip -d $dir $name" and rmdir $dir;
	}
}
