#!/bin/bash

unset LANG
unset LC_CTYPE
unset LC_TIME
date=`date +'%F %T'`
current_path=`pwd`
case "`uname`" in
    Linux)
    abs_path=$(readlink -f $(dirname $0))
    ;;
  *)
    abs_path=`cd $(dirname $0); pwd`
    ;;
esac
cd $abs_path

if [ -d .git ]; then
  revision=`git log -1 --pretty=format:"%H"`
  hostname=`hostname`
  url=`git remote -v | grep origin | grep fetch |  awk '{print $2}'`
  case "`uname`" in
    Darwin)
      version=`cat pom.xml | head -n 10 | egrep -o '<version>5\..*?(-SNAPSHOT)?<' | cut -c 10- | awk -F'<' '{print $1}'`
      ;;
    *)
      version=`cat pom.xml | head -n 10 | grep -oP '<version>5\..*?(-SNAPSHOT)?<' | cut -c 10- | awk -F'<' '{print $1}'`
    ;;
  esac

  if [ "x${RELEASE}" != "x" ];then
    ec="echo $version | sed 's/SNAPSHOT/$RELEASE/g'"
    version=`eval $ec`
  fi
  branch=`git branch --no-color | grep '*' | awk '{print $2}'`
else
  revision="Unknown"
  branch="Unknown"
  version="Unknown"
  url="file://$abs_path"
fi

cat << EOF | \
  sed -e "s/VERSION/$version/" -e "s/DATE/$date/" -e "s|URL|$url|" -e "s/REV/$hexVevision/" -e "s|BRANCH|$branch|" \
      > src/main/java/com/taobao/yugong/common/version/package-info.java
/*
 * Generated by saveVersion.sh
 */
@YuGongVersionAnnotation(version="VERSION", hexVersion="REV", branch="BRANCH", date="DATE", url="URL")
package com.taobao.yugong.common.version;
EOF
cd $current_path