#!/usr/bin/python3
import sys, os.path, re
from subprocess import call, PIPE, Popen

copyright="""\
Format: http://dep.debian.net/deps/dep5
Upstream-Name: wims-help
Source: those files are extracted from an installed Wims service, after
        refreshing the modules from the repository WimsEdu. See the file
        "refresh" in the source package.

%s

Files: debian/*
Copyright: 2011 Georges Khaznadar <georgesk@ofset.org>
License: GPL-2+
 This package 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 package 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 <http://www.gnu.org/licenses/>
 .
 On Debian systems, the complete text of the GNU General
 Public License version 2 can be found in "/usr/share/common-licenses/GPL-2".
"""

if __name__=="__main__":
    path=sys.argv[1]
    indexes=Popen("find %s -type f -name INDEX" %path, shell=True, stdout=PIPE).communicate()[0].decode("utf-8")
    indexes=indexes.strip().split("\n")
    files=""
    for i in sorted(indexes):
        d=os.path.dirname(i)
        f=os.path.basename(i)
        author=Popen("sed -n 's/^author=\\(.*\\)/\\1/ p' %s" %i, shell=True, stdout=PIPE).communicate()[0].strip()
        email=Popen("sed -n 's/^address=\\(.*\\)/\\1/ p' %s" %i, shell=True, stdout=PIPE).communicate()[0].strip()
        copy=Popen("sed -n 's/^copyright=\\(.*\\)/\\1/ p' %s" %i, shell=True, stdout=PIPE).communicate()[0].decode("utf-8").strip()
        assert "GNU GPL" in copy
        lic = "GNU Public License version 2\n see '/usr/share/common-licenses/GPL-2'"
        years=" ".join(re.findall("[-0-9]+", copy))
        files+="Files: %s/*\n" %d
        files+="Copyright: %s %s <%s>\n" %(years, author, email)
        files+="License: %s\n\n" %(lic)

    print (copyright %(files))
    
