package upstream;

use warnings;
use strict;
use autodie;

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

sub mirror_file {
	my ( $url, $file ) = @_;
	print STDERR "mirror $url";
	mirror( $url, $file )
		== RC_NOT_MODIFIED
		&& warn(" not modified\n")
		|| warn(" done ", -s $file, " bytes\n")
		;
}

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";

	mirror_file( $url, $iso );

	$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 $name/iso || sudo mount $iso $mnt -o loop -t iso9660 -v") == 0;
}

sub file {
	my ( $url, $file ) = @_;
	my $path = "$server::base_dir/$file";
	my @file_parts = split m{/}, $file;
	foreach ( 1 .. $#file_parts - 1 ) {
		my $path = splice @file_parts, 0, $_;
		warn "? $path\n";
		mkdir $path unless -e $path;
	}
	mirror_file( $url, "$server::base_dir/$file" );
}

1;
