#!/usr/bin/env bash
log_file=/var/log/hash-files.log
keys_of_interest=("kMDItemFSCreationDate" "kMDItemFSName")
md5_bin=$(which md5sum)
mktemp_bin=$(which mktemp)
DateTimeStamp=$(date +\%D_\%T)

IFS=$'\n'

set -a
source .env 2>&1 > /dev/null
set +a

## Functions
############

write_log () {
#echo "		++ Write to log.
#		+++++++++++++++"
## Use on systems managed with systemd
#	printf 'hash-files:	%s\n' "$1" | systemd-cat
	printf '%s	hash-files:	%s\n' "$DateTimeStamp" "$1" >> $log_file
}



mdls_per_file () {
	file=$1
	unset mdls_properties
	for line in $(mdls $file); do
		old_IFS=$IFS
		unset IFS
		mdls_key=$(printf "%s" $line | cut -d '=' -f 1)
		mdls_value=$(printf "%s" $line | cut -d '=' -f 2)
		if [[ " ${keys_of_interest[*]} " =~ " ${mdls_key} " ]];then
			IFS=$old_IFS
			mdls_properties+=$mdls_value
			unset IFS
		else
			: #echo "Did not print!"
		fi
		IFS=$old_IFS
	done
	old_IFS=$IFS
	echo  $mdls_properties
}


write_per_file () {
#echo "=== Write data to a .csv file. ===
#===================================="
#	cat $temp_csv_file
#	write_log "$temp_csv_file written successfully."
printf 'File: %s\nHash: %s\nMDLS Properties:\t%s\n' $1 $2 $3
}

cleanup () {
	write_log "Cleanup completed successfully."
}

## Main
#######

trap cleanup EXIT

echo "Main Start"
## Create temp file
temp_csv_file=$($mktemp_bin)
## Initialize column names
csv_columns=( "File Path" "File Hash" )
## Populate Columns from keys of interest
echo "Keys of interest:"
echo ${keys_of_interest[@]}
echo "==========================================="
for key in ${keys_of_interest[@]};do
	csv_columns+=( $key )
done
## Print columns to first line of csv
#echo "======= CSV Columns ========"
{ IFS=',';echo "${csv_columns[*]}";IFS=$'\n'
## Loop through files, writing to csv
for file in $(find $Working_Fullpath -maxdepth 1 -type f); do
	hash=$($md5_bin $file | awk '{ print $4 }')
	IFS=',';echo $(mdls_per_file $file);IFS=$old_IFS
#	echo "============= CSV Row =========="
	#echo "$file,$hash,$mdls_properties"
#	write_per_file $file $hash $mdls_properties
done	
} >> $temp_csv_file
cat $temp_csv_file
unset IFS