package upstream;

use warnings;
use strict;
use autodie;

use Data::Dump qw/dump/;
use LWP::Simple qw/mirror RC_NOT_MODIFIED/;
use server;
use once;

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

sub iso {
	my $url = shift;

	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 ) if once::first_time $url;

	$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 files {
	my $url = shift;
	my @files = @_;

	if ( ! @files ) {
		push @files, $1 if $url =~ s{/([^/]+)$}{};
	}

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

	my $path = "$server::base_dir/tftp/$name";
	mkdir $path unless -d $path;

	warn "# files $url ",dump( @files ), " -> $path\n";

	foreach my $file ( @files ) {
		mirror_file( "$url/$file", "$path/$file" )
			if ! -e "$path/$file" || once::first_time( "$url/$file" );
	}
}

1;
