import sys
from os import path
import urllib; from urllib.request import urlretrieve
from subprocess import call

def install_hooks(directory):
    checkstyleUrl = 'https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.36.1/checkstyle-8.36.1-all.jar'
    preCommitUrl = 'https://gist.githubusercontent.com/EdotJ/d512826d5b4fd3e6cdc285b9236511b2/raw/43e5087ed173fd03aab640b0b3db22f11319c623/pre-commit'
    checkstyleName = checkstyleUrl.split('/')[len(checkstyleUrl.split('/')) - 1]
    basePath = path.abspath(directory)
    print("Downloading checkstyle to %s..." % basePath + "/.git/hooks/" + checkstyleName)
    urlretrieve(checkstyleUrl, basePath + "/.git/hooks/" + checkstyleName)
    print("Downloading pre-commit script to %s" % basePath + "/.git/hooks/pre-commit")
    urlretrieve(preCommitUrl, basePath + "/.git/hooks/pre-commit")
    with open(basePath + '/.git/config', 'a+') as gitConfig:
        if ("[checkstyle]" not in gitConfig.read()):
            print("Adding git configurations to .git/config")
            gitConfig.write("[checkstyle]\n")
            gitConfig.write("jar = %s\n" % (basePath + "/.git/hooks/" + checkstyleName))
            gitConfig.write("checkfile = %s\n" % (basePath + "/checkstyle_config.xml"))
    print("Changing permissions for pre-commit. Has to run as root, enter password plz")
    call(["sudo", "chmod", "+x", (basePath + "/.git/hooks/pre-commit")])


if __name__ == "__main__":
    if (len(sys.argv) < 2):
        print("Enter a directory to install hooks")
    else:
        if (path.exists(sys.argv[1])):
            install_hooks(sys.argv[1])

[((10, 15, 10, 38), 'os.path.abspath', 'path.abspath', ({(10, 28, 10, 37): 'directory'}, {}), '(directory)', False, 'from os import path\n'), ((12, 4, 12, 74), 'urllib.request.urlretrieve', 'urlretrieve', ({(12, 16, 12, 29): 'checkstyleUrl', (12, 31, 12, 73): "(basePath + '/.git/hooks/' + checkstyleName)"}, {}), "(checkstyleUrl, basePath + '/.git/hooks/' + checkstyleName)", False, 'from urllib.request import urlretrieve\n'), ((14, 4, 14, 66), 'urllib.request.urlretrieve', 'urlretrieve', ({(14, 16, 14, 28): 'preCommitUrl', (14, 30, 14, 65): "(basePath + '/.git/hooks/pre-commit')"}, {}), "(preCommitUrl, basePath + '/.git/hooks/pre-commit')", False, 'from urllib.request import urlretrieve\n'), ((22, 4, 22, 72), 'subprocess.call', 'call', ({(22, 9, 22, 71): "['sudo', 'chmod', '+x', basePath + '/.git/hooks/pre-commit']"}, {}), "(['sudo', 'chmod', '+x', basePath + '/.git/hooks/pre-commit'])", False, 'from subprocess import call\n'), ((29, 12, 29, 36), 'os.path.exists', 'path.exists', ({(29, 24, 29, 35): 'sys.argv[1]'}, {}), '(sys.argv[1])', False, 'from os import path\n')]