#!/bin/sh

help () echo "Usage: $0 init|track|commit"

if [ $# -ne 1 ] && [ $# -ne 2 ]; then
    help
    exit 1
fi

operation=$1

if [ "$operation" = "init" ]; then
	mkdir -p .sortle/initial/
elif [ "$operation" = "track" ]; then
    if [ "$(ls -a | grep .sortle)" = "" ]; then
        echo "No repo is initialised here. Aborting."
        exit 1
    fi
    if [ $# -ne 2 ]; then
        help
    fi
	target_file=$2
	if [ "$(ls .sortle/initial | grep $target_file)" != "" ]; then
    	echo "File $target_file is already tracked"
    	exit 0
	fi
	cp $target_file .sortle/initial/
elif [ "$operation" = "commit" ]; then
    if [ "$(ls -a | grep .sortle)" = "" ]; then
        echo "No repo is initialised here. Aborting."
        exit 1
    fi
    mkdir .sortle/tmp/
    cp .sortle/initial/* .sortle/tmp/
    for commit in $(ls .sortle/ | grep commit_* | sort -n); do
        for patchfile in $(ls .sortle/$commit | grep .diff); do
            fname=$(echo $patchfile | rev | cut -c 6- | rev)
        	patch .sortle/tmp/$fname < .sortle/$commit/$patchfile
        done
    done
    commit_num=$(ls .sortle/ | grep commit | wc -l)
    commit_num=$((commit_num+1))
    mkdir .sortle/commit_$commit_num
    for file in $(ls .sortle/tmp/); do
		diff .sortle/tmp/$file $file > .sortle/commit_$commit_num/$file.diff
    done
    rm -r .sortle/tmp
fi
