#!/bin/bash
#
# gar
#
# Frontend to the GAR scripts and build system
#
#

VERSION=1.0.0
DATE=20201206

set -e
#set -x

[[ "$GARDIR" ]] || GARDIR=/usr/gar

display_usage () {
   echo
   echo "gar $VERSION ($DATE)"
   echo
   echo "Usage: $(basename $0) command [args] ..."
   echo
   echo "$(basename $0) run a GAR command."
   echo
   echo "'command' can be a gar script or a make target"
   echo "for the current working directory"
   echo
   echo "Type 'gar cmdlist' for a list of available gar scripts."
   echo
   echo "Examples:"
   echo
   echo "$(basename $0) build"
   echo "$(basename $0) newpkg linux 4.19.125"
   echo "$(basename $0) setval glic VERSION 2.28"
   echo
}



#######################################################
#                 Options processing                  #
#######################################################

#while getopts ":Vkp" opt; do
#  case $opt in
#    V)
#      echo "$(basename $0) $VERSION, $DATE"
#      exit 0
#      ;;
#    k)
#      catsearch=1
#      ;;
#    p)
#      fullpath=1
#      ;;
#    \?)
#      echo "$(basename $0): Invalid option: -$OPTARG" >&2
#      display_usage
#      exit 1
#      ;;
#    :)
#      echo "$(basename $0): Option -$OPTARG requires an argument" >&2
#      exit 1
#      ;;
#  esac
#done
#
#shift $(($OPTIND-1))

##### Positional arguments processing #####

if [[ -z "$1" ]]; then
   display_usage
   echo "*** Error: a command must be specified." >&2
   echo
   exit 111
fi

garcmd="$1"

###########################################

main () {

   # Try to find a script first
   scriptdir="${GARDIR}/gar.scripts"

   if [[ -x ${scriptdir}/gar${garcmd} ]]; then
      shift
      ${scriptdir}/gar${garcmd} "$@"
   else
      # If no script was found we treat it as a make target
      make "$garcmd" "$*"
   fi

}

main "$@"
