#!/bin/sh

# This file is used to generate the package-info.java class that
# records the version, revision, branch, user, timestamp, and url

unset LANG
unset LC_CTYPE
unset LC_TIME
user=`whoami`
date=`date`
current_path=`pwd`
bin_abs_path=$(readlink -f $(dirname $0))
project_path=$(readlink -f $(dirname $bin_abs_path/../../../../))
echo "run saveVerion.sh script"
echo "cd to $bin_abs_path for workaround relative path"
cd $bin_abs_path

if [ -d ../../../.svn ]; then
  revision=`svn info | sed -n -e 's/Last Changed Rev: \(.*\)/\1/p'`
  url=`svn info node | sed -n -e 's/URL: \(.*\)/\1/p'`
  # Get canonical branch (branches/X, tags/X, or trunk)
  branch=`echo $url | sed -n -e 's,.*\(branches/.*\)$,\1,p' \
                             -e 's,.*\(tags/.*\)$,\1,p' \
                             -e 's,.*/trunk$,trunk,p'`
  version=`echo $url | sed -n -e 's,.*branches/\(.*\)$,\1,p' \
                             -e 's,.*tags/\(.*\)$,\1,p' \
                             -e 's,.*/trunk$,trunk,p'`
elif [ -d ../../../.git ]; then
  revision=`git log -1 --pretty=format:"%H"`
  hostname=`hostname`
  url="git://${hostname}${project_path}"
  version=`cat ../pom.xml | grep -oP '<version>4\.\d+\.\d+(-SNAPSHOT)?' | cut -c 10-`
  branch=`git branch  | awk '{print $2}'`
else
  revision="Unknown"
  branch="Unknown"
  version="Unknown"
  url="file://$bin_abs_path"
fi
srcChecksum=`find ./ -maxdepth 1 -name '*.sh' | LC_ALL=C sort | xargs md5sum | md5sum | cut -d ' ' -f 1`

cat << EOF | \
  sed -e "s/VERSION/$version/" -e "s/USER/$user/" -e "s/DATE/$date/" \
      -e "s|URL|$url|" -e "s/REV/$revision/" \
      -e "s|BRANCH|$branch|" -e "s/SRCCHECKSUM/$srcChecksum/" \
      > main/java/com/alibaba/otter/shared/common/utils/version/package-info.java
/*
 * Generated by saveVersion.sh
 */
@OtterVersionAnnotation(version="VERSION", revision="REV", branch="BRANCH",
                         user="USER", date="DATE", url="URL",
                         srcChecksum="SRCCHECKSUM")
package com.alibaba.otter.shared.common.utils.version;
EOF

echo "cd to $current_path for continue"
cd $current_path
