#!/usr/bin/env 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 call(args):
    return subprocess.Popen(args,stdout=subprocess.PIPE).communicate()[0].decode()

def git_tags():
    args = ["git", "tag", '-l']
    tags = call(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 call(args).strip().split('\n')

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

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

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


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


def main():
    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 = list(zip(tags,tags))
    else:
        tags = list(zip(tags,tags))
        tags.insert(0,(args.version,'HEAD'))

    for i in range(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('{0} ({1}) {2}; urgency={3}\n'.format(args.name,tag[0],args.codename,args.urgency))

        for line in lines:
            print("  * " + line)

        authorandtime = git_author_and_time(tag[1])
        print(' {0}\n'.format(authorandtime))

        tag = prev

if __name__ == "__main__":
    main()