# encoding=utf-8

# Copyright 2015-2022 Simon McVittie
# Copyright 2015-2016 Alexandre Detiste
# SPDX-License-Identifier: GPL-2.0-or-later

# This version of this file is only used when run uninstalled. It is replaced
# with a generated version during installation.

import os

srcdir = os.path.dirname(
    os.path.dirname(
        os.path.abspath(__file__)
    )
)

with open(os.path.join(srcdir, 'debian', 'changelog'), encoding='utf-8') as fd:
    try:
        from debian.changelog import Changelog
    except ImportError:
        GAME_PACKAGE_VERSION = fd.readline().split('(', 1)[1].split(')', 1)[0]
        if '-' in GAME_PACKAGE_VERSION:
            GAME_PACKAGE_VERSION, GAME_PACKAGE_RELEASE = (
                GAME_PACKAGE_VERSION.rsplit('-', 1)
            )
        else:
            GAME_PACKAGE_RELEASE = ''
    else:
        cl = Changelog(fd, strict=False, max_blocks=1)
        GAME_PACKAGE_VERSION = cl.upstream_version or ''
        GAME_PACKAGE_RELEASE = cl.debian_revision or ''

details = {}
if os.path.isfile('/etc/os-release'):
    with open('/etc/os-release', encoding='utf-8') as release:
        for line in release:
            if '=' not in line:
                continue
            key, value = line.strip().split('=', 1)
            details[key] = value.strip('"')

if os.path.isfile('/etc/debian_version'):
    FORMAT = 'deb'
    DISTRO = 'generic'

# mageia also has a /etc/redhat-release
elif os.path.isfile('/etc/mageia-release'):
    FORMAT = 'rpm'
    DISTRO = 'mageia'

elif os.path.isfile('/etc/redhat-release'):
    FORMAT = 'rpm'
    DISTRO = 'fedora'

elif os.path.isfile('/etc/SuSE-release') or details.get('ID_LIKE') == 'suse':
    FORMAT = 'rpm'
    DISTRO = 'suse'

elif os.path.isfile('/etc/arch-release'):
    FORMAT = 'arch'
    DISTRO = 'arch'

else:
    exit('ERROR: Unknown distribution')

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--distro', default='')
    parser.add_argument('--format', default='')
    parser.add_argument('--version', default='')
    parser.add_argument('--release', default='')
    args = parser.parse_args()

    if args.release:
        GAME_PACKAGE_RELEASE = args.release

    if args.version:
        GAME_PACKAGE_VERSION = args.version

    if args.format:
        FORMAT = args.format

    if args.distro:
        DISTRO = args.distro

    print('# Generated file, do not edit')
    for const in (
        'DISTRO',
        'FORMAT',
        'GAME_PACKAGE_VERSION',
        'GAME_PACKAGE_RELEASE',
    ):
        print('%s = %r' % (const, eval(const)))
