#!/bin/bash
#
#	Init options
#
SIMULATION=0
VERBOSE=0
BUILDIDFILE=
PROJPATH="$(realpath .)"
BINDIR="$(realpath $(dirname $0))"
LIBDIR="$(realpath ${BINDIR}/../libexec/devop-tools)"
[[ -d ${LIBDIR} ]] || LIBDIR="$(realpath ${BINDIR}/../libexec)"
#
#
#
Usage () 
{
	echo -e "\nusage: $(basename $0) [-f <build-id-file> ][-h][-p <project-path> ][-s][-v] [<build-id-file>]\n" >&2
	echo -e "\t-f <build-id-file>\tDefine complete version information and time-stamp" >&2
	echo -e "\t-h\t\t\tThis help output" >&2
	echo -e "\t-p <project-path>\tProject root path [$PROJPATH]" >&2
	echo -e "\t-s\t\t\tSimulation (read-only)" >&2
	echo -e "\t-v\t\t\tVerbose\n" >&2
	exit ${1:-0}
}
#
#	Process command line options
#
while getopts ":f:hp:sv" opt; do
	case $opt in
		f)
			BUILDIDFILE=$OPTARG
			;;
		h)	
			Usage
			;;
   	p)
			PROJPATH="$(realpath $OPTARG)"
			;;
    s)
			SIMULATION=1
    	;;
    v)
    	VERBOSE=1
    	;;
    \?)
			echo "Invalid option: -$OPTARG" >&2
			exit 1
    	;;
	esac
done
shift $((OPTIND-1))
if [ $# -gt 0 ] && [ -f $1 ]; then
	BUILDIDFILE=$1
fi

#
# Process ID
#

GetBuildId ()
{
  local opts=""
  [[ -n $BUILDIDFILE ]] && opts="$opts -f $BUILDIDFILE"
  [[ $SIMULATION -gt 0 ]] && opts="$opts -s"
  [[ $VERBOSE -gt 0 ]] && opts="$opts -v"
  pushd $1 > /dev/null
  eval $2 $opts
  popd > /dev/null
}

#
#	Detect Repository
#

DetectRepository ()
{
  local rootdir="$1"
  [ -d "$rootdir" ] || return
#  echo -e "ROOTDIR:\t$rootdir\n"
  if [ -d "$rootdir/.svn" ]; then
    GetBuildId "$rootdir" "$LIBDIR/build-id.svn"
  elif [ -d "$rootdir/.git" ]; then
    GetBuildId "$rootdir" "$LIBDIR/build-id.git"
  else
  [ "$rootdir" == "/" ] && return
    DetectRepository "$(dirname $rootdir)"
  fi
}

DetectRepository $PROJPATH

