#!/usr/bin/env python3
import os
import subprocess

Import('env')

GSCHEMA_DIR_SUFFIX = 'share/glib-2.0/schemas'
GUI_DIR = 'gui'
FILES_RECORD = '.files.txt'
FILES_RECORD_FULL = os.path.join(GUI_DIR, FILES_RECORD)
PREFIX = env['PREFIX']

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

PYTHON = ARGUMENTS.get('PYTHON', 'python3')

if 'install' in COMMAND_LINE_TARGETS and GetOption('with_gui'):
    python_exe = which(PYTHON)
    if not python_exe:
        print('!! Unable to find {} executable.'.format(PYTHON))
        print('!! Will build no GUI.')
    else:
        if GetOption('with_compile-glib-schemas'):
            env['ENV']['COMPILE_GLIB_SCHEMA'] = '1'
        py_install = env.Command(
            'always.install',
            ['setup.py'],
            'cd {} && {} setup.py install --prefix {} --record {}'.format(
                GUI_DIR,
                python_exe,
                PREFIX,
                FILES_RECORD
            )
        )
        env.Alias('install', py_install)


if 'uninstall' in COMMAND_LINE_TARGETS and GetOption('with_gui'):
    def uninstall_python_module(**kwargs):
        try:
            with open(FILES_RECORD_FULL, 'r') as handle:
                for path in handle:
                    path = path.strip()
                    try:
                        os.remove(path)
                    except OSError as err:
                        print('Unable to delete', path, ':', err)

        except OSError as err:
            print('Could not open {}: '.format(FILES_RECORD_FULL), err)

        if not GetOption('with_compile-glib-schemas'):
            return

        # recompile remaining glib schemas after deleting ours
        print('Recompiling glib schemas')
        gschema_dir = os.path.join(env['PREFIX'], GSCHEMA_DIR_SUFFIX)
        compile_command = [
                'glib-compile-schemas',
                gschema_dir]
        try:
            subprocess.call(compile_command)
        except subprocess.CalledProcessError as err:
            print("Error recompiling glib schemas post uninstall")


    env.Alias('uninstall',
        env.Command(
            FILES_RECORD_FULL, '',
            Action(uninstall_python_module , "Uninstalling recorded files...")
        )
    )
