#!/usr/bin/python

# Copyright (c) 2016, Antonio SJ Musumeci <trapexit@spawn.link>

# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.

# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import sys
import subprocess
import argparse

def git_tags():
    args = ["git", "tag", '-l']
    tags = subprocess.check_output(args)
    tags = [[int(X) for X in tag.split(".")] for tag in tags.split()]
    tags.sort()
    tags.reverse()
    tags = [".".join([str(X) for X in tag]) for tag in tags]
    return tags

def git_log(fromtag,totag):
    args = ['git','log','--no-merges','--oneline',fromtag+'...'+totag]
    return subprocess.check_output(args).strip().split('\n')

def git_author_and_time(tag):
    args = ['git','log','-1','--format=-- %an <%ae>  %cD',tag]
    return subprocess.check_output(args).strip()

def git_version():
    args = ['git','describe','--always','--tags','--dirty']
    return subprocess.check_output(args).strip()

def guess_distro():
    try:
        args = ['lsb_release','-i','-s']
        return subprocess.check_output(args).strip().lower()
    except:
        return 'unknown'


def guess_codename():
    try:
        args = ['lsb_release','-c','-s']
        return subprocess.check_output(args).strip().lower()
    except:
        return 'unknown'


def patch_subprocess():
    if "check_output"  not in dir( subprocess ): # duck punch it in!
        def check_output(*popenargs, **kwargs):
            r"""Run command with arguments and return its output as a byte string.

            Backported from Python 2.7 as it's implemented as pure python on stdlib.

            >>> check_output(['/usr/bin/python', '--version'])
            Python 2.6.2
            """
            process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
            output, unused_err = process.communicate()
            retcode = process.poll()
            if retcode:
                cmd = kwargs.get("args")
                if cmd is None:
                    cmd = popenargs[0]
                error = subprocess.CalledProcessError(retcode, cmd)
                error.output = output
                raise error
            return output

        subprocess.check_output = check_output

def main():
    patch_subprocess()

    parser = argparse.ArgumentParser(description='Generated debian/changelog from git log')
    parser.add_argument('--name',type=str,help='Name of package',required=True)
    parser.add_argument('--version',type=str,help='Place in git history to include upto',default='::guess::')
    parser.add_argument('--distro',type=str,help='Distribution name',default='::guess::')
    parser.add_argument('--codename',type=str,help='Distribution codename',default='::guess::')
    parser.add_argument('--urgency',type=str,help='Urgency',default='medium')

    args = parser.parse_args()

    if args.distro == '::guess::':
        args.distro = guess_distro()

    if args.codename == '::guess::':
        args.codename = guess_codename()

    versuffix = "~"+args.distro+"-"+args.codename

    if args.version == '::guess::':
        args.version = git_version()

    tags = git_tags()

    if args.version in tags:
        idx = tags.index(args.version)
        tags = tags[idx:]
        tags = zip(tags,tags)
    else:
        tags = zip(tags,tags)
        tags.insert(0,(args.version,'HEAD'))

    for i in xrange(0,len(tags)):
        tags[i] = (tags[i][0] + versuffix,tags[i][1])

    tag = tags[0]
    for prev in tags[1:]:
        lines = git_log(tag[1],prev[1])
        if lines == ['']:
            tag = prev
            continue

        print('%s (%s) %s; urgency=%s\n' % (args.name,tag[0],args.codename,args.urgency))

        for line in lines:
            print "  * " + line

        authorandtime = git_author_and_time(tag[1])
        print(' %s\n' % authorandtime)

        tag = prev

if __name__ == "__main__":
    main()
