#!/usr/bin/perl
#############################################################################
# search: Search a file for some content
#         return a json string in the format of an array of objects 
#         [ {"name":"value", "name2":"value2", ...}, {"name":"value", ...} ]
#############################################################################

use CGI "param";

$str = param('search') || param('q');           #obtain HTML entry field

if (! $str)                                     #if no param is entered
{
    print "Content-type: text/html \n\n";
    print "<h3> Please provide username as: URL?q=... </h3> \n";
    exit(0);
}

print "Content-type: text/plain \n";            #text/plain instead of text/html
print "\n";

open (FILE, "< /etc/passwd") || print "Cannot open file - $!";

$output = "[ \n";

####### Search file contents ########
while($line = <FILE>) {

    $line =~ s/"/ /g;                            #if line contains " replace with space

    if ($line =~ /$str/i)                        #if line contains search str
    {    
        @elements = split(':', $line);
        $output .= "\t {";
        if ($elements[0]) {$output .= "\"userid\" :\"$elements[0]\", " ;}
        if ($elements[2]) {$output .= "\"unixid\" :\"$elements[2]\", " ;}
        if ($elements[4]) {$output .= "\"name\"   :\"$elements[4]\", " ;}
        if ($elements[5]) {$output .= "\"homedir\":\"$elements[5]\"  " ;}
        $output .= "}, \n";
    }
}
$output =~ s/\, \n$/ \n/ ;                      #strip off the last comma

$output .= "] \n";                  

print $output;

close(FILE); 

exit(0);