#!/bin/bash
# # # #
# Determine time of last and first Trackevent in file/unit
#
# Why? Because timestamp is not human-readable and one unit can have multiple files.
#
##

function isNumber(){
	re='^[0-9]+$'
	if [[ "$1" =~ $re ]]; then
		return 1
	else
		return 0
	fi
}

function getDates() {
	# gets second/last line timestamp and transform it to date
	# for more files, will get latest/earliest date of all files
	
	date1=`date +%s`
	date2=0
	for file in "$@"; do
		timestamp1=`head -2 "$file" | tail -1 | cut -d';' -f1`
		timestamp2=`tail -1 "$file" | cut -d';' -f1`
		
		isNumber "$timestamp1"
		if [ "$?" != 0 ]; then
			if [ ${timestamp1} -lt ${date1} ]; then
				date1="$timestamp1"
				file1="$file"
			fi
		else
			echo "nonum"
		fi

		isNumber "$timestamp2"
		if [ "$?" != 0 ]; then
			if [ ${timestamp2} -gt ${date2} ]; then
				date2="$timestamp2"
				file2="$file"
			fi
		else
			echo "nonum"
		fi
	done

	if [ ${date1} -lt ${earliest} ]; then
		earliest="$date1"
		earliestFile="$file1"
	fi
	if [ ${date2} -gt ${latest} ]; then
		latest="$date2"
		latestFile="$file2"
	fi

	date1=`date -d @"$timestamp1" +"%Y-%m-%d %T"`
	date2=`date -d @"$timestamp2" +"%Y-%m-%d %T"`
	echo "${date1}		${file1}"
	echo "${date2}		${file2}"
	echo ""
}

function getDatesUnit(){
	for i in "$@"; do
		echo "unit $i"
		files=`ls "$dir"/*unit-$i-* 2> /dev/null` 
		if [ "$?" == 0 ]; then
			getDates $files
		else
			echo "didn't find files"
			echo ""
		fi
	done
}

function getDatesAll() {
	
	earliest=`date +%s`
	latest=0

	getDatesUnit {1..13}


	earliest=`date -d @"$earliest" +"%Y-%m-%d %T"`
	latest=`date -d @"$latest" +"%Y-%m-%d %T"`
	echo "unit all"
	echo "${earliest}		${earliestFile}"
	echo "${latest}		${latestFile}"
}

if [ -z $1 ];then
	dir="."
else
	dir="$1"
	if ! [ -d $dir ]; then
		echo "dir doesn't exist"
		exit
	fi
fi

getDatesAll # > "${dir}/../02-inspect/dates"
