package Debian::ExtRepo::Data;

use Exporter;
use YAML qw/Load LoadFile/;
use LWP::UserAgent;
use File::Temp qw/tempdir tempfile/;

our @ISA = qw/Exporter/;

our @EXPORT_OK = qw/fetch_repodata fetch_config/;

sub fetch_config {
	return LoadFile('/etc/extrepo/config.yaml');
}

sub fetch_repodata {
	my $config = fetch_config;

	my $ua = LWP::UserAgent->new;
	$ua->env_proxy;

	my $url = join('/', $config->{url}, $config->{dist}, $config->{version}, 'index.yaml');

	my $response = $ua->get($url);
	if(!$response->is_success) {
		print "Could not download index YAML file:\n";
		die $response->status_line;
	}

	my $extrepo_yaml = $response->decoded_content;

	$response = $ua->get("$url.asc");
	if(!$response->is_success) {
		print "Could not download YAML file signature:\n";
		die $response->status_line;
	}

	my $extrepo_gpg = $response->decoded_content;
	my $dir = tempdir(CLEANUP => 1);
	my ($yaml_fh, $extrepo_yaml_file) = tempfile(DIR => $dir);
	print $yaml_fh $extrepo_yaml;
	close $yaml_fh;

	my ($gpg_fh, $extrepo_gpg_file) = tempfile(DIR => $dir);
	print $gpg_fh $extrepo_gpg;
	close $gpg_fh;

	system("gpgv", "--keyring", "/etc/extrepo/keyring.gpg", $extrepo_gpg_file, $extrepo_yaml_file) == 0 or die "could not validate gpg signature, exiting\n";

	print "\n\n";

	unlink($extrepo_yaml_file);
	unlink($extrepo_gpg_file);
	
	return Load($extrepo_yaml);
}
