#!/usr/bin/python3

import sys
from pathlib import Path

gitdir = Path('.git')

if not gitdir.is_dir():
    sys.exit(0)

from sh import git
from debian.copyright import Copyright, FilesParagraph, NotMachineReadableError

def detect_license_for(path, c=None):
    if c is None:
        with open('debian/copyright', 'rb') as f:
            c = Copyright(f, strict=False)
    # patterns ending with * do not always match correctly (TODO: why?)
    # remove the * to make sure they do
    if path.endswith('/*'):
        path = path.rstrip('*')
    r = None
    for p in c.all_files_paragraphs():
        if p.files[0] == '*':
            continue
        if p.matches(path):
            r = p
    if r:
        return r.copyright, r.license
    return None, None

def dump_debcargo_copyright(package):
    return git('-C', '.git/debcargo-conf.git', 'cat-file', 'blob',
               f'master:src/{package}/debian/copyright')

confgitdir = gitdir / 'debcargo-conf.git'

if confgitdir.is_dir():
    git('-C', confgitdir, 'fetch', '--depth=1', 'origin', 'master:master')
else:
    git('clone', '--depth=1', 'https://salsa.debian.org/rust-team/debcargo-conf.git',
        '--bare', confgitdir)

vendordir = Path('vendor')

for d in sorted(vendordir.iterdir()):
    pkgdir = d.name
    pkgname = pkgdir.replace('_', '-')
    c, l = detect_license_for(str(d) + '/.')
    #print(pkgdir, l)
    if c is None:
        try:
            cp = dump_debcargo_copyright(pkgname)
            c = Copyright(cp, strict=False)
            p = c.find_files_paragraph('Cargo.toml')
            p.files = ['vendor/' + pkgdir + '/' + f
                       for f in p.files]
            print(p.dump())
        except Exception as e:
            print('Files: vendor/' + pkgdir + '/*')
            print('Copyright: UNKNOWN')
            print('License: UNKNOWN')
            print()
