#!/usr/bin/env python

# This script generates the KDE standard PHP changelog for a KDE Software Compilation
# and Platform release.
# The method used is simply the one described in DOCS.
#
# Written by Michael Pyne <mpyne@kde.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This is the default tag to generate a changelog for. You can override this on
# the command line.
defaultTag = '4.8.5'

import sys, re, subprocess


# Two-digit tags used to be common e.g. 4_2to4_2_1, but 4.3 and on have used full
# three-digit tags in the generated filenames.
def validate(tag):
    return re.search('^\d+\.\d+\.\d+$', tag) != None


def generateChangelog(releaseTag):
    versionParts = releaseTag.split('.')
    if len(versionParts) != 3:
        raise "Somehow invalid version " + releaseTag

    # Get old version
    oldVersionParts = list(versionParts)
    oldVersionParts[2] = str(int(oldVersionParts[2]) - 1)

    oldVersionTag = '_'.join(oldVersionParts)
    newVersionTag = '_'.join(versionParts)
    branchTag = '_'.join(versionParts[0:2])

    outputName = "changelog%sto%s.php" % (oldVersionTag, newVersionTag)
    inputName = "changelog_branch_%s.xml" % branchTag

    print("Generating %s" % outputName)

    try:
        subprocess.check_call(['xsltproc', '--stringparam', 'outputversion', releaseTag,
                               '-o', outputName, 'changelog.xsl', inputName])
        print("Everything apparently worked, but be sure to check svn diff!")
    except (OSError, subprocess.CalledProcessError) as e:
        print("\n\nThere was an error running xsltproc. :(")
        # Uncomment the following if you want the full traceback
        # print e
        sys.exit(1)


# Start
if __name__ == '__main__':
    releaseTag = defaultTag
    if len(sys.argv) > 1:
        releaseTag = sys.argv[1]

    if validate(releaseTag):
        print("Creating changelog for release %s" % releaseTag)
        generateChangelog(releaseTag)
    else:
        if sys.argv[1] in ['-h', '--help']:
            print("This generates the changelog from the XML, just pass the version number")
            print("of the next release, or leave blank for the default (%s)." % defaultTag)
            print("\nUsage: %s [4.x.y]" % sys.argv[0])
        else:
            print("Release tag %s is invalid, should be of the form 4.x.y" % releaseTag)
