#!/usr/pkg/bin/perl

# Copyright (c) 2026 snake_case_nemo <scnemo@sdf.org>
# SPDX-License-Identifier: BSD-2-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use strict;
use warnings;
use feature 'say';
use File::Basename;

use constant ROOT_DIR	    => "/ftp/pub/users/scnemo/phlog";
use constant GOPHER_DIR     => "/users/scnemo/phlog";
use constant SERVER         => "sdf.org";
use constant LOG_FILE       => "../logs/search_access.log";

sub g_say;
sub g_print;
sub g_die;

system("date >> " . LOG_FILE);

my @args = split($", $ENV{QUERY_STRING});
my @files = glob(ROOT_DIR . "/*.txt") or g_die " Cannot read files";
my @results = get_results(@files);
print_results(@results);

sub print_results {
    my @result = @_;

    for my $r (@result) {
        next if scalar(@{ $r->{results} }) == 0;
        my $fname = basename($r->{name});
        say "0$fname\t" . GOPHER_DIR . "/$fname\t" . SERVER . "\t70";
        g_say "[MATCH] $_" for @{ $r->{results} };
    }
}

sub get_results {
    my @files = @_;
    my @results = ();

    # Iterate over all found files. 
    for my $file (@files) {
        open FD, "<", $file or g_die "$file: $!";
        my @fd = <FD>;
        close FD;

        # Create entry object.
        my $entry_obj = {
            name    =>  $file,
            results =>  []
        };
        
        # Look for lines matching all search terms
        # and save the line in results.
        for my $line (@fd) {
            chomp($line);
            # my $pattern = '^' .
            # join('', map { "(?=.*\\b" . quotemeta($_) . "\\b)" } @args);
            # The above pattern will match all args in one line.
            # This one will print the line if any matches.
            my $pattern = join('|', map { "(\\b" . quotemeta($_) . "\\b)" } @args);
            next if $line !~ /$pattern/i;
            push @{ $entry_obj->{results} }, $line;
        }

        # Push entry object to results.
        push @results, $entry_obj;
    }

    return @results;
}

sub g_die($) {
    my ($die_msg) = @_;
    g_say "g_die: $die_msg";
    exit 0;
}

sub g_say($) {
	my ($str) = @_;
	say "i$str";
}

sub g_print($) {
	my ($str) = @_;
	print "i$str";
}
