#!/bin/bash

# Called if input parameters incorrect
usage() 
{
	>&2 echo Insufficient or invalid parameters entered.
	>&2 echo Usage: $0 startDir numDays scriptMode
	>&2 echo valid script modes: 1 = summary, 2 = verbose.
	exit
}

# Summary mode output function.  Outputs contents of arrays formatted and sorted by count descending.
showChanges()
{
for user in $(seq 1 $numusers); do printf "${username[$user]}\t${numFiles[$user]}\n";
	done | sort -k 2 -n -r
}

# Verbose mode output function.  Uses above to extract names sorted by count, then iterates through
# list of files
showSorted()
{
	# Since ls output is shown from directory containing file, we will change directories a lot
	# Since path may be relative, need to return to current directory after each listing.
	curdir="$(pwd)"
	for userName in $(showChanges | cut -f 1); do
		# Retrieve correct index from associative array.
		user=${ownerNumber[$userName]}
		echo ${username[$user]}
		for filenum in $(seq 1 ${numFiles[$user]}); do
			# Format filename to escape special characters / spaces
			file=$(printf '%q' "${fileName[$user,$filenum]}")
			# Separate path to file and base filename.
			filedir="$(dirname $file)"
			filename="$(basename $file)"
			cd "$filedir"
			ls -lt "$filename"
			cd "$curdir"	
		done
		echo
	done
}

# Input validation #1: correct # of arguments
if [ $# -ne 3 ]; then usage; fi
StartDir="$1"
Days="$2"
# Input validation #2: $Days is a number.
[[ $Days =~ [0-9]+ ]]  || usage
# Input validation #3: Mode is 1 or 2.
if [ $3 -eq 2 ]; then
	verbose=true
elif [ $3 -eq 1 ]; then
	verbose=false
else
	usage	
fi

# Temporary storage of raw find listing.
TEMPFILE="/tmp/filesUpdated.tmp"
numusers=0

# Last input validation: make sure directory actually exists.
test -d "$StartDir" 2>/dev/null || usage 
# Store results and suppress errors in favor of our own warning.
find "$StartDir" -mtime $Days > $TEMPFILE 2>/dev/null || >&2 echo WARNING: Could not access all files in path
numfiles=$(cat $TEMPFILE | wc --lines)
# Associative array to store indices of each owner by name for later use.
declare -A ownerNumber
for filenum in $(seq 1 $numfiles); do
	# Note: Done this way because of filenames with spaces.  Requires a lot of disk access.
	file="$(cat $TEMPFILE | head -$filenum | tail -1)"
	# Ignore directories.
	test -d "$file" && continue
	# Retrieve file owner name
	OWNER=$(stat -c %U "$file")
	let "ownerIndex = $numusers + 1" 
	# Test if owner seen before, find/set array index as needed.
	newOwner=true
	for i in $(seq 1 $numusers); do
		if [ ${username[$i]} == "$OWNER" ]; then
			ownerIndex=$i
			newOwner=false
			break;
		fi
	done
	# Note true and false are actually shell commands that return success or failure
	if $newOwner; then
		# Initialize/update arrays
		username[$ownerIndex]=$OWNER
		numFiles[$ownerIndex]=1
		ownerNumber[$OWNER]=$ownerIndex
		let "numusers=$numusers+1"
	else
		# Update file counter
		let "numFiles[$ownerIndex]=${numFiles[$ownerIndex]}+1"
	fi
	fileName[$ownerIndex,${numFiles[$ownerIndex]}]="$file"
done
rm $TEMPFILE
if [ $numusers -gt 0 ]; then
	if $verbose; then
		showSorted
	else
		printf "Owner\tNumber of files changed\n"
		showChanges
	fi
else
	>&2 echo No results found
fi
