#!/usr/bin/env python
# encoding: utf-8

Import('env')
Import('VERSION_MAJOR')
Import('VERSION_MINOR')
Import('VERSION_PATCH')
Import('VERSION_NAME')
Import('create_uninstall_target')

import os
import codecs


def METHOD_NAME(target, source, env):
    text = source[0].get_text_contents()

    with codecs.open(target[0].get_abspath(), 'w') as handle:
        config_h = text.format(
            INSTALL_PREFIX=GetOption('actual_prefix') or GetOption('prefix'),
            HAVE_LIBINTL=env['HAVE_GETTEXT'],
            HAVE_LIBELF=env['HAVE_LIBELF'],
            HAVE_JSON_GLIB=env['HAVE_JSON_GLIB'],
            HAVE_GIO_UNIX=env['HAVE_GIO_UNIX'],
            HAVE_FIEMAP=env['HAVE_FIEMAP'],
            HAVE_XATTR=env['HAVE_XATTR'],
            HAVE_LXATTR=env['HAVE_LXATTR'],
            HAVE_SHA512=env['HAVE_SHA512'],
            HAVE_BIGFILES=env['HAVE_BIGFILES'],
            HAVE_STAT64=env['HAVE_BIG_STAT'],
            HAVE_POSIX_FADVISE=env['HAVE_POSIX_FADVISE'],
            HAVE_BIG_OFF_T=env['HAVE_BIG_OFF_T'],
            HAVE_BLKID=env['HAVE_BLKID'],
            HAVE_SYSBLOCK=env['HAVE_SYSBLOCK'],
            HAVE_LINUX_LIMITS=env['HAVE_LINUX_LIMITS'],
            HAVE_LINUX_FS_H=env['HAVE_LINUX_FS_H'],
            HAVE_BTRFS_H=env['HAVE_BTRFS_H'],
            HAVE_MM_CRC32_U64=env['HAVE_MM_CRC32_U64'],
            HAVE_BUILTIN_CPU_SUPPORTS=env['HAVE_BUILTIN_CPU_SUPPORTS'],
            HAVE_UNAME=env['HAVE_UNAME'],
            HAVE_SYSMACROS_H=env['HAVE_SYSMACROS_H'],
            VERSION_MAJOR=VERSION_MAJOR,
            VERSION_MINOR=VERSION_MINOR,
            VERSION_PATCH=VERSION_PATCH,
            VERSION_NAME=VERSION_NAME,
            VERSION_GIT_REVISION=env['gitrev'].strip()
        )

        handle.write(config_h)


def prepare_c_source(text, escape_percentages=True):
    # Prepare the Python source to be compatible with C-strings
    text = text.replace('"', '\\"')
    text = text.replace('\\n', '\\\\n')
    text = '\\n"\n"'.join(text.splitlines())

    if escape_percentages:
        text = text.replace('%', '%%')
        text = text.replace('%%s', '%s')

    return text


def build_python_formatter(target, source, env):
    text = source[0].get_text_contents()

    with codecs.open('lib/formats/py.py', 'r') as handle:
        py_source = prepare_c_source(handle.read(), False)

    with codecs.open(target[0].get_abspath(), 'w') as handle:
        handle.write(text.replace('<<PYTHON_SOURCE>>', py_source))


def build_sh_formatter(target, source, env):
    text = source[0].get_text_contents()

    with codecs.open('lib/formats/sh.sh', 'r') as handle:
        sh_source = prepare_c_source(handle.read())

    with codecs.open(target[0].get_abspath(), 'w') as handle:
        handle.write(text.replace('<<SH_SOURCE>>', sh_source))


config = env.Command(
    'config.h', 'config.h.in', METHOD_NAME
)

py_formatter = env.Command(
    'formats/py.c', 'formats/py.c.in', build_python_formatter
)

sh_formatter = env.Command(
    'formats/sh.c', 'formats/sh.c.in', build_sh_formatter
)

library = env.Library(
    '../rmlint',
    Glob('*.c')           +
    Glob('checksums/*.c') +
    Glob('checksums/xxhash/*.c') +
    Glob('checksums/blake2/*.c') +
    Glob('checksums/sha3/*.c') +
    Glob('formats/*.c') +
    Glob('fts/*.c')
)

headers = Glob('*.h')
env.Depends(library, [config, py_formatter, sh_formatter])
env.AlwaysBuild(config)
env.AlwaysBuild(py_formatter)
env.AlwaysBuild(sh_formatter)

# Disable this for now until someone
# announces interest in this.
INSTALL_LIBRARY = False

if 'install' in COMMAND_LINE_TARGETS and INSTALL_LIBRARY:
    env.Alias('install', env.Install('$PREFIX/' + GetOption('libdir'), [library]))
    for header in headers:
        env.Alias('install', env.Install('$PREFIX/include/rmlint', [header]))

if 'uninstall' in COMMAND_LINE_TARGETS and INSTALL_LIBRARY:
    create_uninstall_target(env, "$PREFIX/{}/{}".format(
        GetOption('libdir'),
        os.path.basename(str(library[0]))
    ))

    for header in headers:
        create_uninstall_target(env, "$PREFIX/include/rmlint/" + str(header))

Return('library')