#!/usr/bin/env python
# Copyright (C) 2013 Gustavo Noronha Silva <gns@gnome.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

import common
import glob
import os
import subprocess
import sys
import tempfile


def should_update_symbols_file(new, old):
    if not os.path.exists(old):
        return False

    new = open(new).read()
    old = open(old).read()

    if len(new) != len(old):
        return False

    for i, byte in enumerate(new):
        if byte != old[i]:
            return False

    return True

if __name__ == '__main__':
    with tempfile.NamedTemporaryFile() as tmp:
        for file_path in glob.glob(os.path.join(common.build_path('DerivedSources'), 'webkitdom', '*.h')):
            if not os.path.basename(file_path).startswith('WebKit') or file_path.endswith('Private.h'):
                continue

            file_path = file_path.replace('.h', '.symbols')
            with open(file_path) as file_handle:
                tmp.write(file_handle.read())
        tmp.flush()

        gdom_source_path = common.top_level_path('Source', 'WebCore', 'bindings')
        api_break_test_path = os.path.join(gdom_source_path, 'scripts', 'gobject-run-api-break-test')
        subprocess.call([sys.executable, api_break_test_path, os.path.join(gdom_source_path, 'gobject',  'webkitdom.symbols'), tmp.name])

        generated_gdom_symbols_path = os.path.join(common.build_path('DerivedSources'), 'webkitdom', 'webkitdom.symbols')
        if not should_update_symbols_file(tmp.name, generated_gdom_symbols_path):
            source = open(tmp.name, 'r')
            destination = open(generated_gdom_symbols_path, 'w')
            destination.write(source.read())
            destination.close()
            source.close()
