###########################################################################
#
# Shell verification. Try to be robust => very simple.
#
GAG_SHELL_TEST="shell test" || echo "define-version.sh error: You must be under a sh-compatible shell!"
GAG_SHELL_TEST="shell test" || exit 1
unset GAG_SHELL_TEST
#
###########################################################################
#
# Main function definition
#
gagdefver() {
    #
    # Variable and function definitions
    #
    DEFVER_AUTHOR='J. Pety <pety@iram.fr>'
    DEFVER_PROJECT='GILDAS  <http://www.iram.fr/IRAMFR/GILDAS>'
    DEFVER_PROGNAME='gagdefver'
    DEFVER_REPOSITORY="git@git.iram.fr:gildas/src.git"
    DEFVER_MODULE=gildas
    #
    defver_usage() {
	cat <<EOF 1>&2

Define standard directory name conventions used by the "build" and
"source-gag.sh" scripts to enable easy coexistence of different GILDAS
version. To do this, define the following environment variables: 
   GAG_VERS: the Gildas version to be used, e.g. last, month, 31oct,
             nov18, etc...
   GAG_TAG:  the corresponding Git branch or tag, e.g. r18-nov
   SRCDIR:   the corresponding source directory
   EXEDIR:   the corresponding installation directory
   LOGDIR:   the corresponding log directory

usage: source $DEFVER_PROGNAME [version]

options:
  -d     Refine GAG_VERS with tag date if possible
  -n     Do not translate 'day' or 'month' to current day or month, but
         assume that directories (or symlinks to) exist with the input
         version name.
  -h     Show this help page
  -v     Show version information

EOF
	defver_clean
    }
    #
    defver_showversion() {
	echo "$DEFVER_PROGNAME, by $DEFVER_AUTHOR"
	echo "Project: $DEFVER_PROJECT"
	defver_clean
    }
    #
    defver_message() {
	echo "$DEFVER_PROGNAME: $1"
    }
    #
    defver_error() {
	echo 1>&2
	echo "$DEFVER_PROGNAME error: $1" 1>&2
	echo 1>&2
	defver_clean
    }
    #
    defver_clean() {
	unset defver_usage defver_showversion defver_message 
	unset defver_error defver_clean defver_clone
	unset defver_tagdate defver_date
	unset DEFVER_AUTHOR DEFVER_PROGNAME DEFVER_PROJECT
	unset DEFVER_INVERS DEFVER_OUTVERS  DEFVER_OUTTAG
	unset DEFVER_MODULE DEFVER_REPOSITORY
    }
    #
    defver_clone() {
        #
        # * Clone the repository in a temporary directory (env var $tmpdir
        #   is set in return). It is the responsibility of the caller to
        #   destroy this directory when it's done.
        # * Clone the branch named as argument. We perform here a
        #   MINIMALISTIC clone (as we are interested only in the latest
        #   change in a given branch):
        #     - only a bare repo (no need to checkout the files),
        #     - only single branch,
        #     - only last commit in this branch.
        #     - discard tags.
        # * In return the current working directory is the root of the
        #   cloned sources.
        #
        tmpdir=/tmp/$DEFVER_MODULE-$$
        mkdir -p $tmpdir
        \cd $tmpdir
        #
        git clone \
          --bare \
          --branch $1 --single-branch \
          --depth 1 \
          --no-tags \
          $DEFVER_REPOSITORY $DEFVER_MODULE 2> /dev/null || \
          defver_error "cloning branch '$1' from GIT"
        \cd $DEFVER_MODULE
        #
        export tmpdir
        #
    }
    #
    #######################################################################
    #
    # Option parsing
    #
    temp=`getopt "dnhv" "$@"`
    if [ $? -ne 0 ]; then defver_usage; return 2; fi
    eval set -- "$temp"
    unset temp
    while [ $1 != -- ]; do
	case $1 in
	-d) defver_date=1 ;;
	-n) defver_not=1 ;;
	-v) defver_showversion; return 0 ;;
	-h) defver_usage; return 0 ;;
	esac
	shift # Next flag
    done
    shift # Skip double dash
    case $# in
	0) DEFVER_INVERS="default";; # Default version defined below!
	1) DEFVER_INVERS=$1;;
	*) defver_usage;  return 2 ;;
    esac
    set abc; shift # This line to avoid remanence effect in a portable way
    #
    #######################################################################
    #
    # 'day' is an alias for the current day. $GAG_VERS has the form 'ddmmm'
    #
    # 'month' is an alias for the current month. $GAG_VERS has the form
    # 'mmmyy', $GAG_TAG has the form 'ryy-mmm'.
    #
    # 'dev' is equivalent to main trunk.
    #
    case $DEFVER_INVERS in
	day)     if [ "$defver_not" ]; then
                      DEFVER_OUTVERS=$DEFVER_INVERS;
                 else
                      DEFVER_OUTVERS=`date '+%d%b' | tr '[:upper:]' '[:lower:]'`;
                 fi;
                 DEFVER_OUTTAG=$DEFVER_INVERS ;;

	month)   if [ "$defver_not" ]; then
                      DEFVER_OUTVERS=$DEFVER_INVERS;
                 else
                      DEFVER_OUTVERS=`date '+%b%y' | tr '[:upper:]' '[:lower:]'`;
                 fi;
                 DEFVER_OUTTAG=`date '+r%y-%b' | tr '[:upper:]' '[:lower:]'` ;;

        dev)     DEFVER_OUTVERS="dev";
                 DEFVER_OUTTAG="master" ;;

        default) DEFVER_OUTVERS="last";
                 DEFVER_OUTTAG="last" ;;

        *)       if echo $DEFVER_INVERS | grep -q '^[a-z][a-z][a-z][0-9][0-9]$' ; then
                      # Parse e.g. "nov19" as "r19-nov": this adds support for
                      # monthly releases other than current month one.
                      myyear=`echo $DEFVER_INVERS | sed 's/[a-z][a-z][a-z]//'`;
                      mymonth=`echo $DEFVER_INVERS | sed 's/[0-9][0-9]//'`;
                      DEFVER_OUTVERS=$DEFVER_INVERS;
                      DEFVER_OUTTAG="r$myyear-$mymonth";
                      unset myyear mymonth
                 else
                      DEFVER_OUTVERS=$DEFVER_INVERS;
                      DEFVER_OUTTAG=$DEFVER_INVERS;
                 fi
    esac
    #
    #######################################################################
    #
    # Define $GAG_TAG.
    #
    export GAG_TAG=$DEFVER_OUTTAG
    #
    #######################################################################
    #
    # Define $GAG_VERS. Refine GAG_VERS with tag date when asked and
    # possible.
    #
    GAG_VERS=$DEFVER_OUTVERS
    if [ "$defver_date" ]; then
	# Can refine date only if branch already exists!
	if git ls-remote --heads --exit-code $DEFVER_REPOSITORY $GAG_TAG > /dev/null; then
	    curdir="$PWD"
	    defver_clone $GAG_TAG
	    defver_tagdate=`git log -1 --format=%ct $GAG_TAG`  # UNIX timestamp
	    # date -d is not portable: try GNU syntax, else BSD syntax
	    defver_date=$(date -d "@$defver_tagdate" "+%d%b%y %H:%M %Z" 2> /dev/null) || \
	    defver_date=$(date -j -f "%s" $defver_tagdate "+%d%b%y %H:%M %Z" )
	    defver_date=`echo $defver_date | tr '[:upper:]' '[:lower:]'`
	    GAG_VERS="${GAG_VERS} (${defver_date})"
	    \cd $curdir
	    \rm -rf $tmpdir
	    unset tmpdir
	fi
    fi
    export GAG_VERS
    #
    #######################################################################
    #
    if [ -z "$gaghome" ]; then
	gaghome=$HOME/gildas-git
    fi
    export gaghome
    #
    #######################################################################
    #
    SRCDIR=$gaghome/gildas-src-$DEFVER_OUTVERS
    EXEDIR=$gaghome/gildas-exe-$DEFVER_OUTVERS
    LOGDIR=$gaghome/logs/$DEFVER_OUTVERS
    export SRCDIR EXEDIR LOGDIR
    #
    #######################################################################
    #
    defver_clean
}
#
###########################################################################
