#!/bin/sh

OS=$(uname -s)
PROJ_DIR="$(pwd)"
CHEATNT_DIR="$PROJ_DIR/.cheatnt"
FILEPATH=$1

is_empty(){
	file=$1
	filepath=$(get_full_filepath $file $PROJ_DIR)
	filesize=$(stat -f %z "$filepath")
	if [[ $filesize -eq 0 ]]; then echo 1; else echo 0; fi
}

is_tracked(){
	file=$1
	filepath=$(get_full_filepath $file $PROJ_DIR)
	grep -q "$filepath" "$CHEATNT_DIR/tracked"
	if [[ $(echo $?) -eq 0 ]]; then echo 1; else echo 0; fi
}

contains_file(){
	folder=$1
	file=$2
	if [[ -f "$folder/$file" || "$file" == "$folder"* ]]; then
		echo 1
	else
		echo 0
	fi
}

get_full_filepath(){
	file=$1
	folder=$2
	if [[ file == "/"* ]]; then
		echo $file
	else
		echo $folder/$file
	fi
}

track_file(){
	filepath=$1
	inode=$(stat -f "%i" $filepath)
	idev=$(stat -f "%d" $filepath)
	fid="$inode;$idev"
	timestamp=$(date -u +"%F %T")
	echo "$fid;$filepath" >> $CHEATNT_DIR/tracked

	sqlite3 $CHEATNT_DIR/cheatnt.sqlite3 								\
		"INSERT INTO file_events (timestamp, type, action, directory, filepath, fid, old_filepath, diff, handler_type, incident_type, hash) VALUES ('$timestamp', 'FILE EVENT', 'Add', '$PROJ_DIR', '$filepath', '$fid', '', '', '', 'NONE', '<hash>')"
}

if [[ -e $CHEATNT_DIR ]]; then
	if [[ $OS == "Linux" ]]; then
		echo "linux implementation coming soon..."
	elif [[ $OS == "Darwin" ]]; then
		if [[ -f $FILEPATH ]]; then
			istracked=$(is_tracked $FILEPATH)
			iscontained=$(contains_file $PROJ_DIR $FILEPATH)
			isempty=$(is_empty $FILEPATH)
			echo istracked=$istracked iscontained=$iscontained isempty=$isempty
			if [[ $istracked -eq 0 &&  $iscontained -eq 1 && $isempty -eq 1 ]]; then
				filepath=$(get_full_filepath $FILEPATH $PROJ_DIR)
				track_file $filepath
			elif [[ $istracked -eq 1 ]]; then
				echo "$FILEPATH is already tracked."
			elif [[ $iscontained -eq 0 ]]; then
				echo "$FILEPATH is not inside the project folder!"
			elif [[ $isempty -eq 0 ]]; then
				echo "Non-empty files cannot be tracked!"
			else
				echo "something unexpected just happened..."
			fi
		else
			echo "$1 : file does not exist!"
			exit 1
		fi
	elif [[ $OS == "Windows" ]]; then
		echo die trash
	else echo "what OS is this?"
	fi
else
	echo "cheatnt wasn't initialized"
fi
