#!/bin/bash

set -e -u


red="\e[91m"
default="\e[39m"
yellow="\e[93m"
green="\e[92m"

log()
{
    echo -e "${yellow}$1${default}"
}

good()
{
    echo -e "${green}$1${default}"
}

warning()
{
    echo -e "${red}$1${default}"
}

prepareVersion()
{
    log "Preparing new tag: v$major.$minor.$patch_"
    sed -i "s|v[0-9]*\.[0-9]*\.[0-9]*|v$major.$minor.$patch_|g" README.md

    sed -i "s|http://.*/file-.*\..*\t |http://ifm10d20174.intra.ifm/mase/test/file-v$major.$minor.$patch_.txt |g" README.md

    if [ ! -z "$(git status -s)" ]; then
	git commit -m "prepared for new release tag v$major.$minor.$patch_" README.md
    else
	warning "Replaced version information but nothing changed. Check if versions are ok."
    fi
    
    git tag "v$major.$minor.$patch_"
}

inspectVersion()
{
    cut=$1
    patch_=${cut##*.}
    cut=${cut%.*}
    minor=${cut##*.}
    cut=${cut%.*}
    major=${cut##*.}
    cut=${cut%.*}
}

git describe --tags --dirty --long
# Must be empty or something was changed or untracked

if [ ! -z "$(git status -s)" ]; then
    echo -e "${red}Something is dirty here;${default}"
    git status
    exit 22
fi

release=$(git describe --tags --dirty --long)

cut=${release#v*}
cut=${cut%%-*}
last=${release##*-}

if [ "$last" == "dirty" ]; then
   echo "   Its dirty"
    release=${release%-*}
fi

sha=${release##*-}
release=${release%-*}
distance=${release##*-}
release=${release%-*}

inspectVersion $cut

echo "Cut: $cut"
echo "Sha: $sha"
echo "Distance: $distance"
echo "Current/Old Release:   $major . $minor . $patch_"
doPrepareVersion=no

if [ "$#" -gt "0" ]; then
    echo "Version manually"
    inspectVersion ${1#v*}
    doPrepareVersion=yes
elif [ "$distance" != "0" ]; then
    echo "I have to create a new tag"
    let patch_+=1
    doPrepareVersion=yes
fi

if [ "${doPrepareVersion}" == "yes" ]; then
    echo "New Release:   $major . $minor . $patch_"
    prepareVersion
fi

good finished


#---fin------------------------------------------------------------------------
