#!/bin/bash -x
# Author: Kristian Lyngstol <kristian@bohemians.org>

# $ mish /home *mov 1000k

# Find all files, store the names of files in $files
files=$(find "$1" -name "$2" -and -size +"$3")

# Cheat: Move to the search-directory
cd $1

# List all files sorted and output them into a clean log file
ls -l1Srh $files > /tmp/size.txt

# Summarize the file sizes - du would output one line for each file so use
# tail to featch just the last line containing the total. use >> to append
# instead of overwrite
du -hc $files | tail -n1 >> /tmp/size.txt

# Pre-create the owners-list in a global scope
owners=""

# Loop over all files

for a in $files; do

	# The owner is the third column output by ls -l on GNU's ls.
	# Use awk to fetch it instead of cut.
	owner=$(ls -l "$a" | awk '{print $3}')
	
	# add the owner to the "owners" list, possibly duplicating the file
	# owner
	owners="$owners\n$owner"

	# Create the directory, use -p to ignore issues with creating the
	# same directory multiple times.
	mkdir -p /tmp/${owner}

	# Change ownership of everything - the lazy way
	chown -R ${owner} /tmp/${owner}
	
	# Change permissions, don't bother differantiating between files
	# and directories.
	chmod -R 0700 /tmp/${owner}

	# Copy (change cp to mv to move) the file.
	# use basename to get just the file name, not directory structure
	cp "$a" /tmp/${owner}/`basename $a`

	# schedule a rm of the file in 48 hours
	echo rm /tmp/${owner}/`basename $a` | at "now + 48 hours"
done

# create real_owners which are unique entries in $owners
real_owners=$(echo -e "$owners" | uniq)

# loop over user and mail them
for a in $real_owners; do
	# Yeah, we tell them _all_ moved files, not just the ones moved
	# right now. They probably want to know
	echo "Vi har flyttet ting: " $(ls /tmp/$a/) | mail -s "Fra din admin, til deg" $a
done
