#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2022 Simon McVittie
# SPDX-License-Identifier: GPL-2.0-or-later

import os
import subprocess
import sys
from contextlib import suppress

def main(zipfile, *inputs):
    os.environ['TZ'] = 'UTC'

    if 'SOURCE_DATE_EPOCH' in os.environ:
        timestamp = int(os.environ['SOURCE_DATE_EPOCH'])
    else:
        timestamp = None

    files = []

    for json in inputs:
        for ext in [
            'files',
            'groups',
            'json',
            'sha1sums',
            'sha256sums',
            'size_and_md5',
        ]:
            other = os.path.splitext(json)[0] + '.' + ext

            if os.path.exists(other):
                os.chmod(other, 0o644)

                if timestamp is not None:
                    os.utime(other, (timestamp, timestamp))

                files.append(other.encode('utf-8'))

    with suppress(FileNotFoundError):
        os.unlink(zipfile)

    # TODO: We could do this in pure Python too...
    subprocess.run(
        ['zip', zipfile, '-9', '-X', '-q', '-j', '-@'],
        check=True,
        input=b'\n'.join(sorted(files)) + b'\n',
    )

if __name__ == '__main__':
    main(*sys.argv[1:])
