#!/usr/bin/env perl use v5.36.0; use strict; use warnings; use utf8; use Path::Tiny; use Mojo::UserAgent; my $target_dir = shift @ARGV or die 'No target dir passed.'; my $gpg_temp_dir = Path::Tiny::tempdir; my $gpg_bin = 'gpg'; my @args = ( '--command-fd', '0', '--homedir', $gpg_temp_dir ); my $gentoo_pk_id = '13EBBDBEDE7A12775DFDB1BABB572E0E2D182910'; my $stage_destination = path('stage.tar.xz'); my $stage_destination_asc = path($stage_destination . '.asc'); _doNothingIfTargetDirExists($target_dir); _fetchKey($gentoo_pk_id); _trustKey($gentoo_pk_id); _downloadGentooStage($stage_destination, $stage_destination_asc); _verifyStage($stage_destination_asc); _extractStageIntoTarget($target_dir, $stage_destination); sub _extractStageIntoTarget($target, $stage) { system 'mkdir', $target; system 'sudo', 'tar', '-xpvf', $stage, '-C', $target, '--numeric-owner', q/--xattrs-include='*.*'/; } sub _doNothingIfTargetDirExists($target) { if (-e $target) { die "$target exists, doing nothing."; } } sub _verifyStage($stage_asc) { my $return_code = system $gpg_bin, @args, '--verify', $stage_asc; if ($return_code != 0) { die 'Signature is not valid, maybe someone is trying to eavesdrop your connection?'; } } sub _downloadGentooStage($stage, $stage_asc) { if (-e $stage && -e $stage_asc) { return; } my $ua = Mojo::UserAgent->new; my $dom = $ua->get('https://www.gentoo.org/downloads/')->result->dom; for my $h4 ($dom->find('h4')->each) { next if $h4->text !~ /Stage/; my @next_list_groups = $h4->following('div.list-group')->each; my $url; for my $a ($next_list_groups[0]->find('a')->each) { my $inner_url = $a->attr('href'); if ($inner_url =~ /systemd/) { $url = $inner_url; last; } } die 'Unable to find gentoo stage' if (!defined $url); $stage->spew_raw($ua->get($url)->result->body); $stage_asc->spew_raw($ua->get($url . '.asc')->result->body); last; } } sub _fetchKey ($key) { my $return_code = system $gpg_bin, @args, '--recv-keys', $key; if ( $return_code != 0 ) { die 'Unable to fetch gentoo gpg key.'; } } sub _trustKey ($key) { open( my $fh, '|-', $gpg_bin, @args, '--edit-key', $key, 'trust' ); say $fh 5; say $fh 'y'; close $fh; my $return_code = $?; if ( $return_code != 0 ) { die 'Unable to trust gentoo gpg key.'; } }