#!/usr/bin/env rexx

/* Rexx */
Address system "pwd" with output stem pwd.
.environment~pwd = pwd.1

Address system "ls -lAh "||.environment~pwd With output stem dir.
dirlist1 = .array~new()
Do i = 1 to dir.0
    if dir.i~StartsWith("total") then nop
    Else call add_to_array1(dir.i)
End
dirjson1 = .json~new()~toJSON(dirlist1)

say dirjson1~e

Say " "
call SysFileTree .environment~pwd||"/", file., 'BL'
dirlist2 = .array~new()
do i = 1 to file.0
 call add_to_array2(file.i)
end
dirjson2 = .json~new()~toJSON(dirlist2)
Say dirjson2

Exit

add_to_array1: PROCEDURE expose dirlist1
    parse arg attrs filecnt . . filesz . . . filenm
    dirlist1~append(.directory~new())

    dirlist1[dirlist1~last]['name'] = filenm

    if attrs~startsWith("d") then dirlist1[dirlist1~last]['type'] = 'dir'
    else dirlist1[dirlist1~last]['type'] = 'file'

    if attrs~startsWith("d") then NOP
    else dirlist1[dirlist1~last]['bytes'] = filesz
Return dirlist1

add_to_array2: PROCEDURE expose dirlist2
    /*  3/16/25   2:29p         558  -rwxrwxr-x  /home/gmgauthier/Projects/rexx-things/projects/oorexx/params.rex */
    parse arg . . filesz attrs filepath

    filenm = parse_filename(filepath)

    dirlist2~append(.directory~new())
    dirlist2[dirlist2~last]['name'] = filenm

    if attrs~startsWith("d") then dirlist2[dirlist2~last]['type'] = 'dir'
    else dirlist2[dirlist2~last]['type'] = 'file'

    if attrs~startsWith("d") then NOP
    else dirlist2[dirlist2~last]['bytes'] = filesz
Return dirlist2

parse_filename: procedure
  parse arg filepath

  /* Parse the filepath to get just the filename */
  parse var filepath . '/' filename
  do while pos('/', filename) > 0
    parse var filename . '/' filename
  end
return filename

::requires 'json.cls'
