#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2015 Simon McVittie <smcv@debian.org>
# SPDX-License-Identifier: GPL-2.0-or-later

import textwrap

if __name__ == '__main__':
    cin = open('debian/copyright.in', encoding='utf-8')
    copy = open('debian/copyright', 'w', encoding='utf-8')

    copy.write(cin.__next__())
    copy.write(
        '# This file was generated by debian/copyright.py from debian/copyright.in\n'
    )
    copy.write('# Please edit one of those files instead\n')

    for line in cin:
        if line.lower().startswith('include-license:'):
            license = line.split(':', 1)[1].strip()
            with open(license, encoding='utf-8') as lic:
                for line in lic:
                    if line.strip():
                        copy.write('  ' + line)
                    else:
                        copy.write(' .\n')
        elif line.lower().startswith('include-license-wrap:'):
            license = line.split(':', 1)[1].strip()
            with open(license, encoding='utf-8') as lic:
                for line in lic:
                    if line.strip():
                        for l in textwrap.wrap(
                            line,
                            break_long_words=False,
                            initial_indent=' ',
                            subsequent_indent=' ',
                            tabsize=2,
                        ):
                            copy.write(l + '\n')
                    else:
                        copy.write(' .\n')
        else:
            copy.write(line)
    cin.close()
    copy.close()
