+sub hash_cmd() {
+ my $len = length($file_hash);
+ my $cmd;
+
+ $len == 64 and return "$ENV{'MKHASH'} sha256";
+ $len == 32 and return "$ENV{'MKHASH'} md5";
+ return undef;
+}
+
+sub tool_present {
+ my $tool_name = shift;
+ my $compare_line = shift;
+ my $present = 0;
+
+ if (open TOOL, "$tool_name --version 2>/dev/null |") {
+ if (defined(my $line = readline TOOL)) {
+ $present = 1 if $line =~ /^$compare_line /;
+ }
+ close TOOL;
+ }
+
+ return $present
+}
+
+sub select_tool {
+ $custom_tool =~ tr/"//d;
+ if ($custom_tool) {
+ return $custom_tool;
+ }
+
+ # Try to use curl if available
+ if (tool_present("curl", "curl")) {
+ return "curl";
+ }
+
+ # No tool found, fallback to wget
+ return "wget";
+}
+
+sub download_cmd {
+ my $url = shift;
+ my $filename = shift;
+
+ if ($download_tool eq "curl") {
+ return (qw(curl -f --connect-timeout 20 --retry 5 --location),
+ $check_certificate ? () : '--insecure',
+ shellwords($ENV{CURL_OPTIONS} || ''),
+ $url);
+ } elsif ($download_tool eq "wget") {
+ return (qw(wget --tries=5 --timeout=20 --output-document=-),
+ $check_certificate ? () : '--no-check-certificate',
+ shellwords($ENV{WGET_OPTIONS} || ''),
+ $url);
+ } elsif ($download_tool eq "aria2c") {
+ my $additional_mirrors = join(" ", map "$_/$filename", @_);
+ my @chArray = ('a'..'z', 'A'..'Z', 0..9);
+ my $rfn = join '', "${filename}_", map{ $chArray[int rand @chArray] } 0..9;
+
+ @mirrors=();
+
+ return join(" ", "[ -d $ENV{'TMPDIR'}/aria2c ] || mkdir $ENV{'TMPDIR'}/aria2c;",
+ "touch $ENV{'TMPDIR'}/aria2c/${rfn}_spp;",
+ qw(aria2c --stderr -c -x2 -s10 -j10 -k1M), $url, $additional_mirrors,
+ $check_certificate ? () : '--check-certificate=false',
+ "--server-stat-of=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
+ "--server-stat-if=$ENV{'TMPDIR'}/aria2c/${rfn}_spp",
+ "--daemon=false --no-conf", shellwords($ENV{ARIA2C_OPTIONS} || ''),
+ "-d $ENV{'TMPDIR'}/aria2c -o $rfn;",
+ "cat $ENV{'TMPDIR'}/aria2c/$rfn;",
+ "rm $ENV{'TMPDIR'}/aria2c/$rfn $ENV{'TMPDIR'}/aria2c/${rfn}_spp");
+ } else {
+ return join(" ", $download_tool, $url);
+ }
+}
+
+my $hash_cmd = hash_cmd();
+$hash_cmd or ($file_hash eq "skip") or die "Cannot find appropriate hash command, ensure the provided hash is either a MD5 or SHA256 checksum.\n";