#!/usr/bin/env bash
# SPDX-FileCopyrightText: 2026 Marco Allegretti
# SPDX-License-Identifier: EUPL-1.2

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_dir"

fail() {
    printf '%s\n' "$1" >&2
    exit 1
}

[[ -f tools/preview-stubs/CMakeLists.txt ]] || fail "preview QML stubs must have tracked CMake integration"
grep -Fq 'set(SHIFT_INSTALL_PREVIEW_QML_STUBS "AUTO"' tools/preview-stubs/CMakeLists.txt \
    || fail "preview QML stubs must default to AUTO, not unconditional installation"
grep -Fq 'PROPERTY STRINGS AUTO ON OFF' tools/preview-stubs/CMakeLists.txt \
    || fail "preview QML stubs must provide an explicit OFF mode"
grep -Fq 'CMAKE_INSTALL_PREFIX MATCHES "/\\.prefix$"' tools/preview-stubs/CMakeLists.txt \
    || fail "preview QML stubs must be limited to local .prefix installs by default"
grep -Eq 'DESTINATION \$\{KDE_INSTALL_QMLDIR\}' tools/preview-stubs/CMakeLists.txt \
    || fail "preview QML stubs must install into the Qt QML import tree"

while IFS= read -r -d '' qmldir; do
    module_dir="$(dirname "$qmldir")"
    while IFS= read -r line; do
        line="${line%%#*}"
        [[ -n "${line//[[:space:]]/}" ]] || continue

        case "$line" in
            module\ *|plugin\ *|classname\ *|typeinfo\ *|depends\ *|prefer\ *)
                continue
                ;;
        esac

        set -- $line
        qml_file="${3:-}"
        [[ -n "$qml_file" ]] || continue
        [[ -f "$module_dir/$qml_file" ]] || fail "$qmldir declares missing file: $qml_file"
    done < "$qmldir"
done < <(find tools/preview-stubs/qml -name qmldir -print0)

printf 'preview-qml-stubs-ok\n'