#!/usr/bin/perl
# Directory listing file search script
# v1.1 by polprog
# Before use, adjust the $directory variable below - it defines the root
# directory for search. "../" assumes this script is in /cgi-bin/
# and the root for the file listing is "/"
#
# The page is stylized for a mainframe interface, but you can
# customize it as you wish
#
# Released on 3-clause BSD Licence
# 16-08-2022, v1.1: Correct some visual aspects

use strict;
use POSIX qw(strftime);
use CGI;
use File::Find;

my $directory = '../';

my $cgi = CGI->new();
print $cgi->header( -type => 'text/html' );

print "<p><a href=\"../\"><b>dirlist</b></a> search page</p>\n";
print "<p><small>search.pl script by polprog</small></p>";
print "<pre>Opening connection...\n";

my $time = uc strftime("%d-%b-%y %H:%M:%S", localtime);
my $ttynum = int rand(3);

# Customize starting banner, this is displayed in <pre>
print <<EOF;
CONNECT 14400
//////////////////
//  CNT/OS v1.4 //
//////////////////
Chaotic Note Tracking System LOGIN AT $time FROM TTY/SER($ttynum) 
 *  REQUESTED SERVICE IS RESTRICTED. SYSTEM ACCESS IS MONITORED.   *
LOGIN: (automatic login)

AUTOEXEC starting batch mode
SET ACTION/RUN=QUERY
EOF


my $query = $cgi->param('query');
($query) =~ s/^\s+|\s+$//g;


# This is the search form
print<<EOF;
ENTER SEARCH TERM THEN STRIKE ENTER</pre>
<form action="search.cgi" method=get>
	<input type="text" name="query" value=$query />
	<input type="submit" value="Search directory tree"/>
    </form><pre>
EOF
if($query eq ""){

    exit 0;
}

# Error message for too short queries (would generate lots of results
if(length($query) < 3){
    print "CNT/OS POLICY VIOLATION: QUERY TOO SHORT\nNO CARRIER</pre>";
    exit 0;
}

print "SET ACTION/QUERY=SEARCH/$query\n";

my @results;

# File::Find function. for each file whose name matches /$query/ (regex)
# adds it to the results array
find ( sub {
    return unless /$query/;  # Must match query
    push @results, $File::Find::name;
       }, $directory );
my $num_entries = () = @results;


print<<EOF;    
RUN
RESULTS=$num_entries
EOF


# Banner to be displayed when there are no results
if($num_entries == 0){
    print<<EOF;

****************************************
*                                      *
*  SEARCH DID NOT RETURN ANY RESULTS   *
*                                      *
****************************************

NO CARRIER</pre>
EOF
    exit 0;
}else{
    print "LISTING QUERY RESULTS:</pre>";
}
# Results are displayed as a series of links. You can customize it here
print "<h2>Search results for \"$query\":</h2>";
foreach(@results){
    (my $friendly_name = $_) =~ s/^\.\.\///g;
    print "<a href=\"$_\" target=\"_blank\">$friendly_name</a></br>";
    
}    

# Goodbye banner
print<<EOF;
<pre>END OF RESULTS
NO CARRIER</pre>
EOF
