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

APPNAME='va38-gui'
VERSION='0.56.3'

# these variables are mandatory ('/' are converted automatically)
top = '.'
out = 'wbuild'

import os
import re
import shutil

from waflib import Errors
from waflib import Logs
from waflib import Scripting
from waflib import Options
from waflib import Context

def display_msg(conf, msg="", status = None, color = None):
    if status:
        conf.msg(msg, status, color)
    else:
        Logs.pprint('NORMAL', msg)

def options(opt):
    opt.load('compiler_c')

    opt.add_option('--disttype', type=str, default="waf", help="Type of the distribution tarball (waf or meson) to create")
    opt.add_option('--distname', type=str, default=None, help="Name for the distribution tarball")
    opt.add_option('--distsuffix', type=str, default="", help="String to append to the distribution tarball name")
    opt.add_option('--tagdist', action='store_true', default=False, help='Create of git tag for distname')

def configure(conf):
    conf.load('compiler_c')

    conf.env['LIB_M'] = ['m']

    conf.check_cfg(package='x11', args='--cflags --libs')
    conf.check_cfg(package='xcursor', args='--cflags --libs')
    conf.check_cfg(package='xrandr', args='--cflags --libs')
    conf.check_cfg(package='xext', args='--cflags --libs')
    conf.check_cfg(package='freetype2', args='--cflags --libs')
    conf.check_cfg(package='cairo-xlib', args='--cflags --libs')

    VA38GUI_DATA_DIR = os.path.normpath(os.path.join(conf.env['PREFIX'], 'share', APPNAME))
    conf.env['VA38GUI_DATA_DIR'] = VA38GUI_DATA_DIR

    VA38GUI_DOC_DIR = os.path.normpath(os.path.join(conf.env['PREFIX'], 'share', 'doc', APPNAME))
    conf.env['VA38GUI_DOC_DIR'] = VA38GUI_DOC_DIR

    conf.define('PACKAGE_VERSION', VERSION)
    conf.define('VA38GUI_DATA_DIR', VA38GUI_DATA_DIR + '/'),
    conf.define('VA38GUI_DOC_DIR', VA38GUI_DOC_DIR + '/'),
#    conf.define('NK_INCLUDE_DEFAULT_ALLOCATOR', 1)
    conf.write_config_header('config.h')

    display_msg(conf, "==================")
    version_msg = APPNAME + "-" + VERSION

    if os.access('version.h', os.R_OK):
        data = open('version.h').read()
        m = re.match(r'^#define GIT_VERSION "([^"]*)"$', data)
        if m != None:
            version_msg += " exported from " + m.group(1)
    elif os.access('.git', os.R_OK):
        version_msg += " git revision will checked and eventually updated during build"

    display_msg(conf, version_msg)

    display_msg(conf)

def git_ver(self):
    bld = self.generator.bld
    header = self.outputs[0].abspath()
    if os.access('./version.h', os.R_OK):
        header = os.path.join(os.getcwd(), out, "version.h")
        shutil.copy('./version.h', header)
        data = open(header).read()
        m = re.match(r'^#define GIT_VERSION "([^"]*)"$', data)
        if m != None:
            self.ver = m.group(1)
            Logs.pprint('BLUE', "tarball from git revision " + self.ver)
        else:
            self.ver = "tarball"
        return

    if bld.srcnode.find_node('.git'):
        self.ver = bld.cmd_and_log("LANG= git rev-parse HEAD", quiet=Context.BOTH).splitlines()[0]
        if bld.cmd_and_log("LANG= git diff-index --name-only HEAD", quiet=Context.BOTH).splitlines():
            self.ver += "-dirty"

        Logs.pprint('BLUE', "git revision " + self.ver)
    else:
        self.ver = "unknown"

    fi = open(header, 'w')
    fi.write('#define GIT_VERSION "%s"\n' % self.ver)
    fi.close()

def build(bld):
    bld(rule=git_ver, target='version.h', update_outputs=True, always=True, ext_out=['.h'])

    if Options.options.disttype != 'waf':
        return

    obj = bld(features=['c', 'cprogram'])

    obj.includes = ['.', '../include/', '../subprojects/nuklear/include/', '../subprojects/pugl/include/']
    obj.defines = ['HAVE_CONFIG_H', 'NK_INCLUDE_DEFAULT_ALLOCATOR=1', 'NK_INCLUDE_DEFINES_H']
    obj.source = [
        'src/main.c',
        'src/serial.c',
        'src/decode.c',
        'src/nk.c',
        'subprojects/pugl/src/x11.c',
        'subprojects/pugl/src/x11_cairo.c',
        'subprojects/pugl/src/common.c',
        'subprojects/pugl/src/internal.c',
        'subprojects/nuklear/src/nuklear_math.c',
        'subprojects/nuklear/src/nuklear_util.c',
        'subprojects/nuklear/src/nuklear_color.c',
        'subprojects/nuklear/src/nuklear_utf8.c',
        'subprojects/nuklear/src/nuklear_buffer.c',
        'subprojects/nuklear/src/nuklear_string.c',
        'subprojects/nuklear/src/nuklear_draw.c',
        'subprojects/nuklear/src/nuklear_vertex.c',
        'subprojects/nuklear/src/nuklear_font.c',
        'subprojects/nuklear/src/nuklear_input.c',
        'subprojects/nuklear/src/nuklear_style.c',
        'subprojects/nuklear/src/nuklear_context.c',
        'subprojects/nuklear/src/nuklear_pool.c',
        'subprojects/nuklear/src/nuklear_page_element.c',
        'subprojects/nuklear/src/nuklear_table.c',
        'subprojects/nuklear/src/nuklear_panel.c',
        'subprojects/nuklear/src/nuklear_window.c',
        'subprojects/nuklear/src/nuklear_popup.c',
        'subprojects/nuklear/src/nuklear_contextual.c',
        'subprojects/nuklear/src/nuklear_menu.c',
        'subprojects/nuklear/src/nuklear_layout.c',
        'subprojects/nuklear/src/nuklear_tree.c',
        'subprojects/nuklear/src/nuklear_group.c',
        'subprojects/nuklear/src/nuklear_list_view.c',
        'subprojects/nuklear/src/nuklear_widget.c',
        'subprojects/nuklear/src/nuklear_text.c',
        'subprojects/nuklear/src/nuklear_image.c',
        'subprojects/nuklear/src/nuklear_9slice.c',
        'subprojects/nuklear/src/nuklear_button.c',
        'subprojects/nuklear/src/nuklear_toggle.c',
        'subprojects/nuklear/src/nuklear_selectable.c',
        'subprojects/nuklear/src/nuklear_slider.c',
        'subprojects/nuklear/src/nuklear_progress.c',
        'subprojects/nuklear/src/nuklear_scrollbar.c',
        'subprojects/nuklear/src/nuklear_text_editor.c',
        'subprojects/nuklear/src/nuklear_edit.c',
        'subprojects/nuklear/src/nuklear_property.c',
        'subprojects/nuklear/src/nuklear_chart.c',
        'subprojects/nuklear/src/nuklear_color_picker.c',
        'subprojects/nuklear/src/nuklear_combo.c',
        'subprojects/nuklear/src/nuklear_tooltip.c',
        ]
    obj.use = ['M', 'X11', 'XCURSOR', 'XRANDR', 'XEXT', 'FREETYPE2', 'CAIRO-XLIB']
    obj.target = 'va38-gui'

    bld.install_files('${VA38GUI_DATA_DIR}', 'share/va38-gui/va38-display.png')

    bld.install_files('${VA38GUI_DOC_DIR}', 'README.md')

class va38_gui_dist(Scripting.Dist):
    def __init__(self):
        Scripting.Dist.__init__(self)
        if Options.options.distname:
            self.base_name = Options.options.distname
        else:
#            try:
            sha = self.cmd_and_log("LANG= git rev-parse --short HEAD", quiet=Context.BOTH).splitlines()[0]
            self.base_name = APPNAME + '-' + VERSION + "-g" + sha
            if self.cmd_and_log("LANG= git diff-index --name-only HEAD", quiet=Context.BOTH).splitlines():
                self.base_name += "-dirty"
#            except:
#                self.base_name = APPNAME + '-' + VERSION
        self.base_name += Options.options.distsuffix

        #print self.base_name

        if Options.options.distname and Options.options.tagdist:
            ret = self.exec_command("LANG= git tag " + self.base_name)
            if ret != 0:
                raise waflib.Errors.WafError('git tag creation failed')

    def get_base_name(self):
        return self.base_name

    def get_excl(self):
        excl = Scripting.Dist.get_excl(self)

        excl += ' ' + out

        excl += ' **/.gitmodules'
        excl += ' **/.gitattributes'
        excl += ' subprojects/**/.editorconfig'
        excl += ' subprojects/**/.clang-format'
        excl += ' subprojects/**/.clang-format-ignore'
        excl += ' subprojects/**/.clang-tidy'
        excl += ' subprojects/**/.clant.json'

        excl += ' GTAGS'
        excl += ' GRTAGS'
        excl += ' GPATH'
        excl += ' GSYMS'

        excl += ' share/va38-gui/Raleway-Bold.ttf'
        excl += ' share/va38-gui/va38-display-photo.jpg'
        excl += ' share/va38-gui/va38-display-photo.png'
        excl += ' share/va38-gui/va38-display-photo.xcf'
        excl += ' share/va38-gui/va38-display.svg'

        excl += ' GNUmakefile.dist'

        if Options.options.disttype == 'waf':
            # meson is not used in distribution tarballs for waf
            excl += ' **/meson.build'
            excl += ' **/meson_options.txt'
            excl += ' va38-gui-*-meson.tar.gz'
            excl += ' GNUmakefile.meson'

        if Options.options.disttype == 'meson':
            # waf is not used in distribution tarballs for meson
            excl += ' wscript'
            excl += ' waf'
            excl += ' verify-sig_waf.sh'
            excl += ' va38-gui-*-waf.tar.bz2'

        # strip autotools files, not used in distribution tarballs for waf and meson
        excl += ' **/Makefile.am'
        excl += ' **/configure.ac'
        excl += ' va38-gui-*-autotools.tar.gz'

        # subproject files that will not be needed for build
        excl += ' **/.github/'
        excl += ' **/.travis.yml'
        excl += ' **/.gitlab-ci.yml'
        excl += ' subprojects/nk_pugl/cmake/'
        excl += ' subprojects/nk_pugl/CMakeLists.txt'
        excl += ' subprojects/nk_pugl/include/'
        excl += ' subprojects/nk_pugl/example/'
        excl += ' subprojects/pugl/test/'
        excl += ' subprojects/pugl/examples/'
        excl += ' subprojects/pugl/.editorconfig'
        excl += ' subprojects/pugl/.includes.imp'
        excl += ' subprojects/pugl/.reuse/dep5'
        excl += ' subprojects/pugl/bindings/cpp/'
        excl += ' subprojects/pugl/doc/'
        excl += ' subprojects/pugl/subprojects/'
        excl += ' subprojects/pugl/resources/'
        excl += ' subprojects/pugl/scripts/'
        excl += ' subprojects/pugl/src/mac.h'
        excl += ' subprojects/pugl/src/mac.m'
        excl += ' subprojects/pugl/src/mac_cairo.m'
        excl += ' subprojects/pugl/src/mac_gl.m'
        excl += ' subprojects/pugl/src/mac_stub.m'
        excl += ' subprojects/pugl/src/mac_vulkan.m'
        excl += ' subprojects/pugl/src/stub.h'
        excl += ' subprojects/pugl/src/win.c'
        excl += ' subprojects/pugl/src/win.h'
        excl += ' subprojects/pugl/src/win_cairo.c'
        excl += ' subprojects/pugl/src/win_gl.c'
        excl += ' subprojects/pugl/src/win_stub.c'
        excl += ' subprojects/pugl/src/win_vulkan.c'
#        excl += ' subprojects/pugl/include/pugl/gl.h'
#        excl += ' subprojects/pugl/include/pugl/glu.h'
#        excl += ' subprojects/pugl/include/pugl/stub.h'
#        excl += ' subprojects/pugl/include/pugl/vulkan.h'
        excl += ' subprojects/pugl/src/x11_gl.c'
        excl += ' subprojects/pugl/src/x11_stub.c'
        excl += ' subprojects/pugl/src/x11_vulkan.c'
        excl += ' subprojects/nuklear/example/'
        excl += ' subprojects/nuklear/demo/'
        excl += ' subprojects/nuklear/extra_font/'
        excl += ' subprojects/nuklear/doc/'
        excl += ' subprojects/nuklear/include/nuklear/stb_image.h'
        excl += ' subprojects/nuklear/clib.json'
        excl += ' subprojects/nuklear/Makefile.nuklear'
        excl += ' subprojects/nuklear/src/Readme.md'
        excl += ' subprojects/nuklear/src/HEADER.md'
        excl += ' subprojects/nuklear/src/build.py'
        excl += ' subprojects/nuklear/src/paq.bat'
        excl += ' subprojects/nuklear/src/paq.sh'
        excl += ' subprojects/nuklear/src/nuklear_knob.c'
        excl += ' subprojects/stb/stb_image_resize_test/'
        excl += ' subprojects/stb/data/'
        excl += ' subprojects/stb/deprecated/'
        excl += ' subprojects/stb/tests/'
        excl += ' subprojects/stb/tools/'
        excl += ' subprojects/stb/docs/'
        excl += ' subprojects/stb/stb_c_lexer.h'
        excl += ' subprojects/stb/stb_connected_components.h'
        excl += ' subprojects/stb/stb_divide.h'
        excl += ' subprojects/stb/stb_ds.h'
        excl += ' subprojects/stb/stb_dxt.h'
        excl += ' subprojects/stb/stb_easy_font.h'
        excl += ' subprojects/stb/stb_herringbone_wang_tile.h'
        excl += ' subprojects/stb/stb_hexwave.h'
# used       excl += ' subprojects/stb/stb_image.h'
        excl += ' subprojects/stb/stb_image_resize2.h'
        excl += ' subprojects/stb/stb_image_write.h'
        excl += ' subprojects/stb/stb_include.h'
        excl += ' subprojects/stb/stb_leakcheck.h'
        excl += ' subprojects/stb/stb_perlin.h'
        excl += ' subprojects/stb/stb_rect_pack.h'
        excl += ' subprojects/stb/stb_sprintf.h'
        excl += ' subprojects/stb/stb_textedit.h'
        excl += ' subprojects/stb/stb_tilemap_editor.h'
        excl += ' subprojects/stb/stb_truetype.h'
        excl += ' subprojects/stb/stb_vorbis.c'
        excl += ' subprojects/stb/stb_voxel_render.h'

#        print(repr(excl))
        return excl

    def execute(self):
        shutil.copy('./' + out + '/version.h', "./src/")
        try:
            super(va38_gui_dist, self).execute()
        finally:
            os.remove("./src/version.h")
            pass
