# ldata <- read.csv('logfile.csv', header = F)
# names(ldata) <- c('date_time', 'username', 'filesystem', 'disk_allocated', 'disk_used', 'percent_used')
# ldata$quota_usage <- ldata$disk_used/ldata$disk_allocated

library(Hmisc)
library(pastecs)
library(psych)
library(plyr)

driver <- function(path, user = NULL, mode = c('quota'), ...) {
#   lfdata <- read.csv(path, header = F)
#   names(lfdata) <- c('date_time', 'username', 'filesystem', 'disk_allocated', 'disk_used', 'percent_used')
  lfdata <- read.table(path)
  f_list <- list(...)
  #sink('p.txt')
  print(lapply(f_list, function(f) f(lfdata, task = mode)))
  #sink()
  #unlink('p.txt')
}

userSummaries <- function(lfdata, task = c('quota')){
  names(lfdata) <- c('username', 'date', 'time', 'filesystem', 'disk_allocated', 'disk_used')
  lfdata <- core(lfdata, mode = task)
  operations <- c(summary, stat.desc, describe)
  summaries <- lapply(operations, function(f) f(lfdata))
  summaries[[length(summaries) + 1]] <- describeBy(lfdata, group = lfdata$filesystem)
  summaries
  #lapply(summaries, write, "post", append=TRUE)
}

overallAnalyses <- function(lfdata, task = c('quota')){
  names(lfdata) <- c('username', 'date', 'time', 'filesystem', 'disk_allocated', 'disk_used')
  operations <- c(summary, core)
  lfdata <- lapply(operations, function(op) op(lfdata, mode = task))
  #lapply(lfdata, print)
  lfdata
}

topTenQuota <-  function(lfdata, task) {
  tt <- lfdata[rev(tail(order(lfdata[2]), 10)), ]
  names(tt) <- c('Top Ten Quota', 'Percent Quota Used')
  row.names(tt) <- seq(nrow(tt))
  tt
}

topTenChurn <-  function(lfdata, task) {
  tt <- lfdata[rev(tail(order(lfdata[2]), 10)), ]
  names(tt) <- c('Top Ten Churn', 'Percent Quota Used')
  row.names(tt) <- seq(nrow(tt))
  tt
}

core <- function(lfdata, mode) {
  if('quota' %in% mode) {
    lfdata$quota_usage <- lfdata$disk_used/lfdata$disk_allocated
    lfdata
  }
  if('churn' %in% mode) {
    lfdata$churn_rate <- vector('numeric', length(lfdata$disk_used))
    for(user in unique(lfdata$username)){
      for(i in 1:length(lfdata[lfdata$username == user,]$disk_used)){
        if(i > 1)
          lfdata[lfdata$username == user,]$churn_rate[i] <- 
          (lfdata[lfdata$username == user,]$disk_used[1] - lfdata[lfdata$username == user,]$disk_used[i])/lfdata[lfdata$username == user,]$disk_used[1]
      }
    }
    print(lfdata)
  }
}

