#!/usr/bin/perl

# This extension will turn URLs into references, like
# this: [5]
#
# To echo the URL of such a reference, as well as write
# it to a file (to be used, for example by w3m), use
# ./echo_URL.pl

use strict;
use warnings;
use Irssi;

sub ignore_html_msg {
    my ($server, $data, $nick, $address) = @_;
    my ($target, $text) = split(/ :/, $data, 2);
    if ($text =~/http/) {
        my $string = $text;
        my $marker = "http";
        my $start = index($string, $marker);
        my $end_str = substr $string, $start;
        my $end = length $end_str;
        if ($end_str =~ /[\s\n()]/) { my $end = $-[0]; }
        my $URL = substr $end_str, 0, $end;
        my $home_path = $ENV{"HOME"};
        my $URL_file = "$home_path/.irssi/scripts/.irssi_URLs.txt";
        system("echo '$URL' >> $URL_file");
        my $before_URL_str = substr $string, 0, $start;
        my $after_URL_str  = substr $end_str, $end;

        my $lines = 0;
        open(my $fh, "<", "$URL_file")
            or die "Cannot open < $URL_file: $!";
        while (<$fh>) { $lines++; }
        close FILE;

        $text="$target :$before_URL_str"."[URL $lines]"."$after_URL_str";
        Irssi::signal_continue($server, $text, $nick, $address);
    }
}

Irssi::signal_add("event privmsg", "ignore_html_msg");
