package upstream;

use warnings;
use strict;
use autodie;

use LWP::Simple qw/mirror RC_NOT_MODIFIED/;
use server;

our $just_once;

sub iso {
	my $url = shift;

	return if $just_once->{$url}++;

	my $name = (caller(1))[3];
	$name =~ s{config::}{} || die "caller isn't package config !";

	warn "$name $url";

	my $dir = "$server::base_dir/iso";
	mkdir $dir unless -e $dir;

	my $file = $1 if $url =~ m{/([^/]+\.iso$)}i;
	die "can't find iso file in $url" unless $file;

	my $iso = "$dir/$file";

	print STDERR "$name mirror $url";
	mirror( $url, $iso )
		== RC_NOT_MODIFIED
		&& warn(" not modified\n")
		|| warn(" done ", -s $iso, " bytes\n")
		;

	$file =~ s{\.iso$}{}i;
	my $mnt = "$server::base_dir/tftp/$name";
	mkdir $mnt unless -d $mnt;
	$mnt .= '/iso';
	mkdir $mnt unless -d $mnt;

	system("mount -t iso9660 | grep $mnt || sudo mount $iso $mnt -o loop -t iso9660 -v") == 0;
}

1;
