#!/usr/bin/env python
#=====================================================================================
# Get data from a server file - one record at a time
# Display to an html form
#=====================================================================================
import os
import cgi                                  #cgi 
import cgitb                                #cgi with traceback error handling
import time                                 #to convert modification date/time
import pwd                                  #to get the user/owner of the file                                  
import grp                                  #to get the user/owner group name                                  
 
cgitb.enable()
 
print("Content-Type: text/html \n")         #required http response header (w/ extra line)

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

dir = str(elements.getvalue('dir'))         #directory name

#======================================================================================
# listDir: list all files in the directory
#======================================================================================
def listDir(dir):
    if dir=='None': dir = '.'                    #if no directory, use current dir 

    print('<br>')
    print("You can enter a directory name at end of <b>url?dir=<i>name</b></i>")

    print("<h2>Directory Listing -<br>")
    print("<font size=+1>"+ os.path.abspath(dir) +"</font></h2>")
    print("<hr>")
    
    files = os.listdir(dir)                     #get list of files in directory (.. not included)

    files.sort()                                #for descending use x.sort(reverse=True)

    print("<table style='background-color:cccccc'>")
    print("<tr bgcolor=tan>", end='')
    print("<th width=200>Name<th width=100>Size<th width=25><th width=200>Last Modified<th width=200>Last Accessed<th>Owner/Group<th>Permissions")

    parentDir = dir +'/..'                                            # .. is not in the list
                                                                      #hardcoded it
    print("<tr><td>", end='')                                                  
    print("<img src=/~sultans/python/demo/file/folder.gif>")                                       
    print("<a href=2listDir_web.py?dir="+ parentDir +">Parent Directory</a><br>")        

    for file in files:
        fullpath = dir +"/"+ file                                     #create a full path
    
        print("<tr><td>", end='')
                  
        if (os.path.isdir(fullpath)):                                 #regular directory
            print("<img src=/~sultans/python/demo/file/folder.gif>")
            print("<a href=2listDir_web.py?dir="+ fullpath +'>'+ file +"</a><br>", end='')

        elif (os.path.isfile(fullpath)):                              #regular file  
            print("<img src=/~sultans/python/demo/file/file.gif>")
            print("<a href="+ fullpath +'>'+ file +"</a><br>", end='')

        filesize = os.path.getsize(fullpath)                          #get file size 
        print("<td align=right><b>" + str(filesize) + "</b> Bytes", end='')
        print("<td> ", end='')
        
        lastModified  = os.path.getmtime(fullpath)                    #number of millisec since 1970  
        print("<td> " + time.ctime(lastModified), end='')             #readable date/time
        
        lastAccessed  = os.path.getatime(fullpath)                    #number of millisec since 1970  
        print("<td> " + time.ctime(lastAccessed), end='')             #readable date/time

        stats        = os.stat(fullpath)                              #an object of file properties

        owner_id     = stats.st_uid                                   #get the uid property (user id)
        owner_struct = pwd.getpwuid(owner_id)                         #get info struct for that user id 
        owner_name   = owner_struct.pw_name                           #get the pw_name property (user name)
        print("<td align=center> " + owner_name, end='')

        group_id     = stats.st_gid                                   #get the gid property (group id)
        group_struct = grp.getgrgid(group_id)                         #get info struct for that group id
        group_name   = group_struct.gr_name                           #get the gr_name property (group name)
        print(" / "  + group_name, end='')
        
        permissions = stats.st_mode                                   #get the st_mode property 
        permissions = oct(permissions)                                #convert to octal
        permissions = str(permissions)[-3:]                           #take last 3 digits  
        print("<td align=center> " + permissions)
        
    print("</table>")
    print("<hr>")
#======================================================================================

listDir(dir)                               #call he above function



#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/s/sultans/web/python/demo')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================