import sys
import os
import stat
from pathlib import Path

PYTHON_BIN = sys.executable
HOOK_SCRIPT_PATH = Path(".hooks/kicad_cli_tools.py")
HOOK_TYPE = "pre-push"

HOOK_PATH = Path(f".git/hooks/{HOOK_TYPE}")

# used if the hook path already exists we dont want to over write anything you have in there
# we would append however all of the default hooks have and `exit 0` which means it wont run
OLD_HOOK_PATH = Path(f".git/hooks/{HOOK_TYPE}-old")

if (os.path.exists(HOOK_PATH)):
    os.rename(HOOK_PATH, OLD_HOOK_PATH)

with open(HOOK_PATH, "w") as txt:
    txt.writelines([
        "#!/bin/sh\n", #shebang
        f"{PYTHON_BIN} {HOOK_SCRIPT_PATH}\n"
        "exit 0\n" #make sure she closes
    ])

# make sure its executable
st = os.stat(HOOK_PATH)
os.chmod(HOOK_PATH, st.st_mode | stat.S_IEXEC)