1import subprocess
2import sys
3import os
4
5def check_git_exists():
6    try:
7        # Check if Git is installed
8        subprocess.call(["git", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
9    except OSError:
10        return False
11    return True
12
13def install_git():
14    if sys.version_info[0] == 2:
15        version_cmd = subprocess.call
16    else:
17        version_cmd = subprocess.run
18
19    # Install Git based on the operating system type
20    system = sys.platform.lower()
21    if "linux" in system:
22        version_cmd(["sudo", "apt-get", "install", "git"])
23    elif "darwin" in system:
24        version_cmd(["brew", "install", "git"])
25    elif "win" in system:
26        print("Please manually install Git and ensure it is added to the system PATH.")
27        sys.exit(1)
28
29def check_file_changes(filepath):
30
31    # Use Git to check the file status
32    result = subprocess.Popen(["git", "status", "--porcelain", filepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
33    out, _ = result.communicate()
34
35    # Return True if the file has changes
36    return bool(out.decode('utf-8'))
37
38def revert_to_original(filepath):
39    # Use Git to revert the file to its original state
40    subprocess.call(["git", "checkout", filepath])
41
42def startup_check():
43    file_path = os.getcwd() + "/ra/fsp/src/bsp/cmsis/Device/RENESAS/Source/startup.c"
44    python_executable = 'python' if sys.version_info[0] == 2 else 'python3'
45
46    # Check if Git is installed, if not, try to install it
47    if not check_git_exists():
48        print("Git not detected, attempting to install...")
49        install_git()
50
51    # Check if Git is installed after the installation attempt
52    if not check_git_exists():
53        print("Git installation failed. Please manually install Git and add it to the system PATH.")
54        sys.exit(1)
55
56    # Check if the file has changes
57    if check_file_changes(file_path):
58        # If changes are detected, revert the file to its original state
59        revert_to_original(file_path)
60    # else:
61    #     print "File {file_path} is unchanged."
62
63if __name__ == "__main__":
64    startup_check()
65