#! /usr/bin/perl -w
use strict;
use HTML::LinkExtor;
use LWP::Simple;

# Saves the url page after, changing the absolute links to the local path

die "Usage: linkFix.pl URL base-URL dir(name of the base directory)\n" if ($#ARGV != 2);
my ($url,$base,$dir) = @ARGV;
die "The url should be a HTML file\n" if(! $url=~ m/\.htm(l*)$/);
die "The base should be a directory\n" if($url=~ m/\/.+?\.+?$/);
$base =~ s/\/$//; # remove / at the end if needed

# Get url and extract links:
my %link2fix;
my $parser = HTML::LinkExtor->new(undef, $url);
my $content = get($url);
die "couldn't get url $url\n" if (! $content);
$parser->parse($content);

# check all links:
my @links = $parser->links;
foreach my $linkarray (@links) {
    my @element  = @$linkarray;
    my $elt_type = shift @element;
    while (@element) {
      my ($attr_name , $attr_value) = splice(@element, 0, 2);
      # add absolute links within the base url to the list:
      $link2fix{$attr_value}++ if ($attr_value =~ m/^$base/);
    }
}

# Find the place to save the file: 
my $location = `pwd`;
chomp($location);
(my $relative = $location) =~ s/.*$dir//;
my $n = ( $relative =~ tr/\//\//); # count number of directories to go up
while($n>0){ # go to the base directory
  chdir "../";
  
  $n--;
}
my $path=`pwd`;
chomp($path);
chdir $location; # back to the directory we started in

# Replace absolute links - with the local path:
foreach my $link (keys %link2fix) {
  (my $new = $link) =~ s/$base//; $new =~ s/^\///;  
  $new  = $path."/".$new;
  # if a directory, link to index.html
  $new .= "/index.html"  unless( $new =~ m/\/.*\..*$/);
  # replace absolute links:
  $content =~ s/$link/$new/g;
}

# ave the HTML to a file:
(my $fileName = $url) =~ s/.*\///;
open (OUT, ">$fileName") or die "Can't open $fileName\n";;
print OUT $content;
close(OUT);
