#!/bin/sh
# determines the version of the sources
# usage: version <source directory>

# set -x

srcdir="$1"

# if we're building via CI from a protected tag, that is our version
if test "${CI_COMMIT_REF_PROTECTED}" = "true" && ! test -z "${CI_COMMIT_TAG}"; then
    echo "${CI_COMMIT_TAG}" | sed -e s/^v//
    exit 0
fi

# set version parts to defaults for CVS snapshot
major_version=`cat ${srcdir}/major_version`
minor_version_proto=`cat ${srcdir}/minor_version`
DATE=`date +%Y%m%d`

#echo $major_version
#echo $minor_version

bzr_count_revisions()
{
    srcdir="$1"
    limit="$2"

    test -z "$limit" || limit="-l $limit"

    count=$(bzr log -n 0 --line $limit "${srcdir}" 2>/dev/null | wc -l)
    echo $count
}

# *TODO* once we get our superproject up on launchpad (and thus get saner branch nicks), use branch nicks for $major_version
# Check if bzr is installed, and if the path is versionned
bzr >/dev/null 2>&1
# But for now, ignore it
if test $? -eq 0 && test -d ${srcdir}/.bzr
#if test 1 -eq 0
then
    # Crappily, we can't rely on revision numbers to do anything
    # ( ie. when one merges then pushes, the last revno might be lower than originally)
    # So we count revisions, including merged ones, also including fools which have empty
    # lines with only "revno: 15" in their commit messages
    revno=$( bzr revno ${srcdir} 2>/dev/null)    
    revcount=$( bzr_count_revisions ${srcdir} )
    lca=$revno
    lcaz=$revcount
    versioned=#
    branchurl=$( bzr info ${srcdir} 2>/dev/null | sed -ne 's/^  parent branch: \(.*\)$/\1/p' )


    # We will check this branch diverged, and/or if tree changed
    bzrmissingcout=$( cd ${srcdir} && bzr missing --this 2>/dev/null )
    missing=$?
    bzr diff ${srcdir} --quiet >/dev/null 2>&1
    changed=$?
        

    if test ${missing} -eq 1
    # if it diverged:
    then
        # Count the revisions we added locally
        localrevisions=$( echo "${bzrmissingcout}" | sed -ne '2,1s/[^0-9]//gp' )
        # See how many steps it is, with the fool's number
        stepsbackwards=$( bzr_count_revisions ${srcdir} ${localrevisions} )
        # And start dancing.
        minor_version=_alpha_z$(( ${revcount} - ${stepsbackwards} ))_${DATE}
        # Set last common ancestors
        lca=$(( ${revno} - ${localrevisions}))
        lcaz=$(( ${revcount} - ${stepsbackwards} ))
        srcchanged=#
    elif test ${missing} -eq 0 && ( test ${changed} -eq 1 || test ${changed} -eq 2 )
    then
        # If a change was made and no more revision was added, just use revision fool's number plus build date
        minor_version=_alpha_z${revcount}_${DATE}
        # And this is versionned too
        srcchanged=#
    elif test ${missing} -eq 0
    then
        # If really no change was made, use the fool's number, with tag if any
        # So check if we have tags
        revno=$(bzr revno ${srcdir})
        tag=$(bzr tags -r $revno | awk '{ print $1 }')
        if test ${tag}
        then
            # If it is tagged, use the tag
            minor_version=_alpha_z${revcount}_${tag}
        else
            # If not, use fool's number only
            minor_version=_alpha_z${revcount}
        fi
        # That's versioned as well
    else
        # Otherwise, this is just not versionned
        versioned=
    fi

    if test $versioned
    then
        branchnick=$( cd ${srcdir}; bzr nick )
        revid=$( bzr testament | sed -ne 's/^revision-id: \(.*\)/\1/p' )
    fi
fi

# try to get a good guess about which branch we're on
GIT_BRANCH="alpha"

if test -e "${srcdir}/.git"; then
    # check for a tag
    cd $srcdir
    # todo: once we have make tags, consider just git describe --tags as version ID.
    if tag=`git describe --tags --candidates=0` > /dev/null 2>&1; then
        major_version=`echo ${tag} | sed -e s/version_// -e s/release_//`
        minor_version=""
        DATE=""
    else
      git update-index --refresh > /dev/null
      if git diff-index --quiet HEAD --; then
            # local checkout clean, just use revno
            DATE=_z`git rev-list HEAD --count`
        else
            # local changes, add date
            DATE=_z`git rev-list HEAD --count`_$DATE
        fi
    fi

    GIT_BRANCH=`git -C ${srcdir} rev-parse --abbrev-ref HEAD`
fi
test -z "${CI_COMMIT_BRANCH}" || GIT_BRANCH=${CI_COMMIT_BRANCH}

if test -z "$minor_version"
then
    test -z "$DATE" || minor_version=`echo ${minor_version_proto} | sed -e "s,DATE,$DATE," -e "s,YYYYMMDD,$DATE,"`
fi

if test "${CI_COMMIT_REF_PROTECTED}" = "true"; then
    # determine alpha/beta/rc status based on branch
    if echo ${GIT_BRANCH} | grep -q "^beta"; then
        minor_version=`echo ${minor_version} | sed -e s,alpha,beta,`
    elif echo ${GIT_BRANCH} | grep -q "^release"; then
        minor_version=`echo ${minor_version} | sed -e s,alpha,rc,`
    fi
fi

echo $major_version$minor_version
