#!/usr/bin/env python
# nocturne.in
#
# Copyright 2026 Jeffry Samuel
# Copyright 2026 Philippe Normand
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import os
import sys
import gettext
import subprocess
import gi

VERSION = 'uninstalled'

gettext.install('nocturne', '')

def mtime(path):
    return os.stat(path).st_mtime

if __name__ == '__main__':

    # Make sure blp files are compiled.
    for (dirname, _subdirs, files) in os.walk('src/ui'):
        for filename in files:
            in_file = os.path.join(dirname, filename)
            basename, ext = os.path.splitext(in_file)
            if ext != '.blp':
                continue
            out_file = f'{basename}.ui'
            if os.path.isfile(out_file) and mtime(out_file) >= mtime(in_file):
                continue
            subprocess.check_call(['blueprint-compiler', 'compile', '--output', out_file, in_file])

    # Make sure the GResource file is compiled.
    compiled_resource_file = os.path.join('src', 'nocturne.gresource')
    if not os.path.isfile(compiled_resource_file) or mtime(os.path.join('src', 'nocturne.gresource.xml')) > mtime(compiled_resource_file):
        subprocess.check_call(['glib-compile-resources', 'nocturne.gresource.xml'], cwd='src')

    # Make sure the GSettings file is compiled.
    compiled_gsettings_file = os.path.join('data', 'gschemas.compiled')
    if not os.path.isfile(compiled_gsettings_file) or mtime(os.path.join('data', 'com.jeffser.Nocturne.gschema.xml')) > mtime(compiled_gsettings_file):
        subprocess.check_call(['glib-compile-schemas', 'data'])
    os.environ['GSETTINGS_SCHEMA_DIR'] = 'data'

    from gi.repository import Gio
    resource = Gio.Resource.load(compiled_resource_file)
    resource._register()

    sys.path.insert(0, 'src')
    from src import main

    sys.exit(main.main(VERSION))
