#!/usr/bin/python3

import argparse
import json
import os
import subprocess
import sys


def get_top_level_dir():
    top_level_dir = subprocess.Popen(
        ['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE
    ).communicate()[0].decode('utf-8').strip()
    return top_level_dir

def make_executable(f):
    task = subprocess.Popen(
        ['chmod', '+x', f], stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    err = task.communicate()[1]
    return err

def run_checks():
    print("Initializing tests before pushing...")
    try:
        import openwisp_utils
    except:
        raise ImportError(
            "'openwisp_utils' failed to import. Make sure all dependencies "
            "are installed and virtual environment is activated."
        )

    # Trigger checks and report if they failed
    try:
        task = subprocess.Popen([f'{REPO_ROOT_DIR}/run-qa-checks', '--pre-push'])
        task.communicate()
        if task.returncode:
            print("---------------------------")
            print(
                "Some checks failed. Please make sure they pass, "
                "or use '--no-verify' to skip them"
            )
            sys.exit(1)
    except FileNotFoundError:
        print("Could not access 'run-qa-checks'")


def install_hook():
    hook_file = os.path.join(HOOKS_DIR, 'pre-push')
    symlink = os.path.islink(hook_file)
    if symlink and os.path.exists(hook_file):
        print('Symlink already exists')
    else:
        if symlink:
            os.unlink(hook_file)
        os.symlink(os.path.abspath(__file__), hook_file)
        print("Symlink created, 'pre-push-hook' has been set up!")

    # Make the hook file executable
    err = make_executable(hook_file)
    if err:
        raise ValueError(err)


def main(args=None):
    global REPO_ROOT_DIR, HOOKS_DIR
    REPO_ROOT_DIR = get_top_level_dir()
    HOOKS_DIR = os.path.join(REPO_ROOT_DIR, '.git', 'hooks')
    parser = argparse.ArgumentParser()
    parser.add_argument('remote', nargs='?', help='provided by git before push')
    parser.add_argument('url', nargs='?', help='provided by git before push')
    parser.add_argument(
        '--install', action='store_true', default=False,
    )
    args = parser.parse_args(args=args)
    if args.install:
        return install_hook()
    run_checks()


if __name__ == '__main__':
    main()
