#!/usr/bin/env python3

import argparse
import json
import os
import os.path
import sys
import yaml

try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

ignored = [
    'gi-docgen',  # gi-docgen isn't typically installed in flatpaks
    'xeme',  # xeme hasn't had a full release yet
]

parser = argparse.ArgumentParser(
    prog='check_flatpak_dependencies',
    description='checks that the flatpak dependencies match the wrap files',
    epilog='This should probably only be ran by meson as a test')

parser.add_argument(
    'project_info',
    type=argparse.FileType('r'),
    help='the meson introspect project info filename')
parser.add_argument(
    'flatpak_manifest',
    type=argparse.FileType('r'),
    help='the flatpak manifest filename')

args = parser.parse_args()

# Load the subprojects
try:
    data = json.loads(args.project_info.read())
    subprojects = data['subprojects']
except Exception as exp:
    print(f'failed to read the project info: {exp}')
    sys.exit(1)

# Load the modules
try:
    raw = args.flatpak_manifest.read()
    _, ext = os.path.splitext(args.flatpak_manifest.name)
    data = None

    if ext in ['.yml', '.yaml']:
        data = yaml.load(raw, Loader=Loader)
    elif ext == '.json':
        data = json.loads(raw)

    raw_modules = data['modules']
except Exception as exp:
    print(f'failed to read the flatpak manifest: {exp}')
    sys.exit(1)

# rebuild modules into a dictionary to make lookups faster
modules = {m['name']: m for m in raw_modules}

# Now iterate through the subprojects and make sure they're all in the manifest
# and have the correct version. This doesn't verify checksums as we don't have
# those, but there's no way a checksum should ever match across versions so
# this should be fine.
failed = False
for subproject in subprojects:
    name = subproject['name']

    if name in ignored:
        continue

    if name not in modules:
        print(f'failed to find a flatpak module named {name}')
        sys.exit(1)

    module = modules[name]
    source = module['sources'][0]

    if subproject['version'] not in source['url']:
        print('version %s of %s was not found in the source url "%s"' %
              (subproject['version'], name, source['url']))
        failed = True

if failed:
    sys.exit(1)
