#!/bin/bash
# Anna Kutch (akutch@g.clemson.edu)
# CPSC 4240 HW2 Script

# init variables 
startDir=$1
amtTime=$2
mode=$3
count=0

# make sure there's a correct number of arguments
if (( $# < $"3" )); then
  echo "Usage: [starting dir] [amt time] [script mode]"
  exit 0
fi

# OUTPUT will be a list in the form:
#     <count of files> <user>
#
# find $startDir -mtime -$amtTime -ls : find the files modified within $amtTime
#                          -type f    : it is a file (not a directory)
# awk '{print $5}'                    : get the user name field only
# sort -r                             : sort in descending order 
# uniq -c                             : print the count for unique user names
# awk '{printf ("%s\t%s\n", $2, $1)}' : print the name followed by the number

OUTPUT="$(find $startDir -mtime -$amtTime -type f -ls | awk '{print $5}' | sort -r | uniq -c | awk '{printf ("%s\t%s\n", $2, $1)}')"

# for script mode 1 (summary mode):
if(($mode==1)); 
  then
  printf "%-20s\tNumber of files changed\n" "Owner"
  for i in $OUTPUT; do

    # print the number of modified files
    if(($count%2)); 
      then 
        # count%2 = 1 -- file count
        printf "$i\n"
      
      # print the user name
      else 
        # count%2 = 0 -- user name 
        printf "%-20s\t" $i
      fi
    let "count++"
  done
fi

# for script mode 2 (verbose mode):
if(($mode==2));
  then

  # VOUTPUT will be a list of filenames
  #
  # find $startDir -mtime -$amtTime -ls : find the files modified within $amtTime
  #                          -type f    : it is a file (not a directory)
  # awk '{print $11}'                   : print the file name

  VOUTPUT="$(find $startDir -mtime -$amtTime -type f -ls | awk '{print $11}')";
  
  # for each unique person...
  for i in $OUTPUT; do 
    # print the files associated with the user   
    if(($count%2)); then 
      # only print the files for the specified user
      echo "$(ls -lt $VOUTPUT | grep $username)"
      
      # print and set the user name
      else 
        # count%2 = 0 -- user name 
        printf "\n%-20s\n" $i
        username="$i"
      fi
    let "count++"
  done
fi