#!/usr/bin/env python3
#=========================================================================================
# 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", ...} ]
#========================================================================================= 
import sys
import cgi                                  #cgi 
import cgitb                                #cgi with traceback error handling
import json

cgitb.enable()
 
elements = cgi.FieldStorage()               #obtain the http parameters

str = elements.getvalue('q')                #string to search for

if not str:                                 #if no param was entered
    print("Content-type: text/html \n")
    print("<h3> Please provide username as: URL?q=... </h3> \n")
    sys.exit(0)

inFile = '/etc/passwd'                      #the file to read
array  = []                                 #create an array

#========================================================================================
# search: search a file for a given str, if found, add to array
#========================================================================================
def search(fileIn, str, array):
 
    input = open(fileIn,'r')                            #Open file for reading
    
    for rec in input:                                   #loop thru the data rows
        if str.lower() in rec.lower():
            rec = rec.rstrip()                          #strip trailing newline
            row = rec.split(':')                        #split the record on ,
            dict = {}                                   #create a dictionary
            if row[0]: dict['userid']  = row[0]         #if element exists, add to dictionary
            if row[2]: dict['unixid']  = row[2]
            if row[4]: dict['name']    = row[4]
            if row[5]: dict['homedir'] = row[5]
            array.append(dict)                          #append each dict to the array
                
    input.close()                                       #close the file

#===================================================================================
# main code
#===================================================================================
search(inFile, str, array)

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

json = json.dumps(array, indent=4)              #convert array of dictionaries to JSON string

print(json)                                     #print (send back) the JSON string