#!/usr/bin/env python3
"""Script for generating the Makefiles."""

import os
import sys
import shutil
import subprocess

PROJECTNAME = "Pitivi"

ROOTDIR = os.path.abspath(os.path.dirname(__file__))
MAKEFILE_TMPL = """all:
\tcd %(build_dir)s && %(ninja)s

install:
\tcd %(build_dir)s && DESTDIR="${DESTDIR}" %(ninja)s install

check:
\tcd %(build_dir)s && %(ninja)s test

validate:
\tcd %(build_dir)s && %(ninja)s validate

dist:
\tcd %(build_dir)s && %(ninja)s dist

clean:
\trm -Rf %(build_dir)s
\trm Makefile
"""


def accept_command(commands):
    """Checks if @command --version works."""
    for command in commands:
        try:
            subprocess.check_output([command, "--version"])
            return command
        except FileNotFoundError:
            pass

    return None


def install_pre_commit_hook():
    """Installs the pre commit hook."""
    os.chdir(ROOTDIR)
    try:
        os.remove(os.path.join(ROOTDIR, ".git", "pre-commit"))
    except FileNotFoundError:
        pass

    os.symlink(os.path.join(os.path.pardir, os.path.pardir, "pre-commit.hook"),
               os.path.join(ROOTDIR, ".git", "pre-commit"))
    try:
        subprocess.check_call(["pre-commit", "install"])
    except (FileNotFoundError, subprocess.CalledProcessError):
        print("Please install pre-commit from http://pre-commit.com/ before"
              " proposing patches")


def configure_meson():
    """Configures meson and generate the Makefile."""
    meson = accept_command(["meson", "meson.py"])
    if not meson:
        print("Install mesonbuild to build %s: http://mesonbuild.com/\n"
              "You can simply install it with:\n"
              "    $ sudo pip3 install meson" % PROJECTNAME)
        exit(1)

    ninja = accept_command(["ninja", "ninja-build"])
    if not ninja:
        print("Install ninja-build to build %s: https://ninja-build.org/"
              % PROJECTNAME)
        exit(1)

    build_dir = os.path.join(ROOTDIR, "mesonbuild")
    shutil.rmtree(build_dir, True)
    os.mkdir(build_dir)
    os.chdir(build_dir)

    try:
        subprocess.check_call([meson, "../"] + sys.argv[1:])
    except subprocess.CalledProcessError:
        exit(1)

    with open(os.path.join(ROOTDIR, "Makefile"), "w") as makefile:
        makefile.write(MAKEFILE_TMPL %
                       {"build_dir": build_dir,
                        "ninja": ninja})

if __name__ == "__main__":
    configure_meson()
    if os.path.exists(os.path.join(ROOTDIR, ".git")):
        install_pre_commit_hook()
