#!/usr/bin/env python3
# Generate AppStream metainfo file from music player identification (.mpi) files
#
# (C) 2024 Martin Pitt <mpitt@debian.org>
#
# 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 2 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/>.

import configparser
import sys


def parse_mpi(mpi: str, modaliases: set[str]):
    """Collect DeviceMatches from MPI file and format as modalias"""

    cp = configparser.RawConfigParser()
    assert cp.read(mpi, encoding='UTF-8')

    try:
        matches = cp.get('Device', 'devicematch')
    except configparser.NoOptionError:
        return

    for match in matches.split(';'):
        # AppStream format: usb:v1111pAAAAd*
        try:
            (subsystem, vid, pid) = match.split(':')
        except ValueError:
            continue
        modaliases.add(f'usb:v{vid.upper()}p{pid.upper()}d*')

#
# main
#

modaliases: set[str] = set()
for f in sys.argv[1:]:
    parse_mpi(f, modaliases)

print("""<?xml version="1.0" encoding="UTF-8"?>
<component>
  <id>org.freedesktop.media_player_info</id>
  <metadata_license>MIT</metadata_license>
  <name>media-player-info</name>
  <summary>Media player identification files</summary>
  <description>
    <p>media-player-info is a repository of data files describing
    media player (mostly USB Mass Storage ones) capabilities. These
    files contain information about the directory layout to use to add
    music to these devices, about the supported file formats, and so
    on.</p>

    <p>The music player capabilities are now described in *.mpi files
    (which are ini-like files), together with udev rules to identify
    these devices.</p>
  </description>
  <url type="homepage">https://gitlab.freedesktop.org/media-player-info/media-player-info</url>
  <provides>""")

for match in sorted(modaliases):
    print(f'    <modalias>{match}</modalias>')

print("""  </provides>
</component>""")
