#!/usr/bin/env python
#=====================================================================================
# Display list of files in a directory (and sub-directory) recursively
# Directory name comes from web input as in: url?dir=dirname  
# Display to an html page
#=====================================================================================
import os
import cgi                                  #cgi 
import cgitb                                #cgi with traceback error handling
import time                                 #to convert modification date/time
import stat                                 #to get file properties                                 
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
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>Recursive Directory Listing Starting at -<br>")
print("<font size=+1>"+ os.path.abspath(dir) +"</font></h2>")
print("<hr>")

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

space = ' '                                     #used for indentation
    
#======================================================================================
# listDir: list all files in the directory
#======================================================================================
def listDir(dir):
    
    global space                                #access the global space variable

    files = os.listdir(dir)                     #get list of files in directory (.. not included)

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

    space +='    '          #add 4 spaces for indentation

    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(space + "<a href=3listDir_recursive_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(space + "<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)

        if (os.path.isdir(fullpath)):                                 #recursive call
            listDir(fullpath)

    space = space[0:len(space)-24]          #take out 4 spaces from indentation
        

        
#======================================================================================

listDir(dir)                               #call he above function

print("</table>")
print("<hr>")



#=== 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
#=================================================================================