#!/usr/local/bin/kermit +
#
# f t p l o g
#
# Analyzes wuftpd-format log (including Kermit FTP-format transaction log).
# Prints top 5 files and the number of times each was accessed.
# Prints histogram of number of access vs number of files.
# Each record contains blank-separated fields; the filename is the 9th field.
#
# Requires:    C-Kermit 7.0 Beta.08 or later.
# Illustrates: Associative arrays, file i/o, word splitting, numeric sorting.
#
# An associative array, file<>, is built up of filenames and counts.
# When complete, the file<> array is converted to 2 regular arrays, &a and &b.
# &a and &b are sorted numerically by count in descending order.
# The top 5 files are listed.
# An associate array, hist<>, is created to build the histogram of counts.
# The histogram is converted, sorted, and listed.
#
# Author: F. da Cruz, Columbia University, July 1999

local line name \%n \%m \%f            ; Local variables
.default = /var/log/ftpd.log
if eq "\v(osname)" "Linux" .default = /var/log/xferlog
if def \%1 assign \%f \fcontents(\%1)
if not def \%f asg \%f \m(default)     ; Name of log file
fopen /read \%c \%f                    ; Open the log file
if fail exit 1 Can't open \%f          ; Check
echo Reading: \%f...                   ; Let use know what's happening
while true {                           ; Loop through records
    fread /line \%c line               ; Read a record
    if fail break                      ; Check for EOF
    increment \%m                      ; Count this record
    .name := \fword(\m(line),9,{ })    ; Extract filename from this record
    _increment file<\m(name)>          ; Count an access for this file
}
fclose \%c                             ; Close the file
echo Records: \flpad(\%m,5)            ; Tell user how many records
.\%n := \faaconvert(file,&a,&b)        ; Convert associative array to &a, &b
echo Files:   \flpad(\%n,5)            ; Tell how many files
echo
echo Top 5 Files:
array sort /reverse /numeric &b &a     ; Sort array &a and &b according to &b
for \%i 1 \%n 1 {                      ; List top 5 files and build histogram
    if ( <= \%i 5 ) echo { \%i. \&a[\%i]: \&b[\%i]}
    _increment hist<\&b[\%i]>
}
echo
echo { Hits Files}                     ; Print histogram heading
.\%n := \faaconvert(hist,&a,&b)        ; Convert hist<> to &a and &b
array sort /numeric &a &b              ; Sort &a and &b according to &a
for \%i 1 \%n 1 {                      ; List each member
    echo \flpad(\&a[\%i],5) \flpad(\&b[\%i],5)
}
exit 0
