#!/bin/bash

# Aren't we directly at version?
TAG=$(git tag | grep -F $(git describe))
if [ -n "$TAG" ]; then
  echo $TAG
  exit 0
fi

# Get version tag
# Uses 'git log ...' insted of 'git tag --merged' to support older distros
TAG=$(git log --oneline --pretty=format:"%d" \
    | grep -Eo '^ \(tag:\ v[[:digit:]]+.*(,|\))' \
    | head -n 1 \
    | sed -n 's/^ (tag:\ v//p' | sed -n 's/\(,.*\|)\)//p')

HASH=$(git rev-parse --short=12 HEAD)

# Add branch info if not passed via command line
if [ -z "${BRANCH}" ]; then
  # There is also --show-current but it's too new to be portable.
  BRANCH=$(git branch | sed -n 's/^[*] //p' | grep -v 'HEAD detached')
fi

# Found a branch
if [ -n "$BRANCH" ]; then
  LENGTH=$(git log --oneline v$TAG..HEAD | wc -l)
  echo $TAG+branch.$(echo $BRANCH | sed 's/[^a-zA-Z0-9]/./g').${HASH}
  exit 0
fi

echo $TAG+detached.${HASH}
exit 0
