#!/usr/bin/python2
from subprocess import Popen, PIPE
from re import match, sub
from sys import argv, getfilesystemencoding
from getopt import getopt
from commit import commit

def check_for_untracked():
	cmd = ["git", "status"]
	p = Popen(cmd, stdout=PIPE, stderr=PIPE)
	stdout, stderr = p.communicate()
	res = stdout.split("\n")
	for line in res:
		line = line.strip()
		if(match("Untracked files:", line)):
			return True
	return False

def check_for_changes():
	cmd = ["git", "status"]
	p = Popen(cmd, stdout=PIPE, stderr=PIPE)
	stdout, stderr = p.communicate()
	res = stdout.split("\n")
	for line in res:
		line = line.strip()
		if(match("Changes not staged for commit:", line)):
			return True
	return False


def get_git_log():
	cmd = ["git", "log", "--encoding=UTF-8", "-1"]
	p = Popen(cmd, stdout=PIPE, stderr=PIPE)
	stdout, stderr = p.communicate()
	res = stdout.split("\n")
	ret = []
	for line in res:
		line = line.strip()
		ret.append(line)
	return ret

def get_commit_list(git_log):
	ret = []
	git_commit = []
	first_run = True
	for line in git_log:
		if match("^commit ", line):
			if first_run:
				first_run = False
			else:
				ret.append(commit(git_commit))
				git_commit = []
		if len(line) > 0:
			git_commit.append(line)
	ret.append(commit(git_commit))
	return ret

def generate_include_file(file_name, commit_list, local_changes, untracked_files):
	if(len(commit_list) > 0):
		f = open(file_name, "w")
		f.write("/* Generated include file */\n\n")
		f.write("#ifndef GIT_COMMIT_H\n")
		f.write("#define GIT_COMMIT_H\n\n")
		f.write("#define CURRENT_COMMIT\t")
		f.write("\"" + commit_list[0].hash() + "\"\n")
		f.write("#define AUTHOR\t\t")
		f.write("\"" + commit_list[0].author() + "\"\n")
		f.write("#define LOCAL_CHANGES\t")
		if(local_changes):
			f.write("\"YES\"\n")
		else:
			f.write("\"NO\"\n")
		f.write("#define UNTRACKED_FILES\t")
		if(untracked_files):
			f.write("\"YES\"\n")
		else:
			f.write("\"NO\"\n")
		f.write("\n#endif /* GIT_COMMIT_H */\n")
		f.close()

def main(argv):
	local_changes = check_for_changes()
	untracked_files = check_for_untracked()
	log_list = get_git_log()
	commit_list = get_commit_list(log_list)
	generate_include_file("source/firmware/git_commit.h", commit_list, local_changes, untracked_files)

if __name__ == "__main__":
	main(argv[1:])

