#!/bin/bash
#
# garsetval
#
# Change the value of a GAR package Makefile variable
#
#

VERSION=1.0.0
DATE=20201206

set -e
#set -x

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

display_usage () {
   echo
   echo "garsetval $VERSION ($DATE)"
   echo
   echo "Usage: $(basename $0) <name> <var> <value>"
   echo
   echo "$(basename $0) set the variable <var> to <value> inside the"
   echo "Makefile for the GAR package <name>."
   echo
   echo "Examples:"
   echo
   echo "$(basename $0) linux DESCRIPTION \"Linus Torvald's Linux kernel\""
   echo "$(basename $0) 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 "$3" ]]; then
   display_usage
   echo "*** Error: all arguments must be specified." >&2
   echo
   exit 111
fi

pkgname="$1"
varname="$2"
varval="$3"

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

main () {
   echo "Finding package directory for '$pkgname'..."
   pkgdir=$(garfind -p "$pkgname")
   pkgmakefile="${pkgdir}/Makefile"
   var_regex="^[[:blank:]]*(${varname}[[:blank:]]*=[[:blank:]]*).*"

   # We use the ASCII record separator character so
   # the user can confidently use values containing
   # /, |, #, etc. Watch for the mostly "write-only"
   # sed invokation below.
   fsep=$(echo -en "\x1E")

   if ! [[ -d $pkgdir ]]; then
      echo
      echo "*** Error: could not find the package directory for '$pkgname'" >&2
      echo
      exit 1
   fi

   if ! grep -E -q "$var_regex" "$pkgmakefile"; then
      echo
      echo "*** Error: '$varname' was not found in $pkgmakefile" >&2
      echo
      exit 1
   fi

   echo "Original value:"
   echo "  $(grep -E "$var_regex" "$pkgmakefile")"
   sed -r -i "s${fsep}${var_regex}${fsep}\1${varval}${fsep}g" "$pkgmakefile"
   echo "Changed to new value:"
   echo "  $(grep -E "$var_regex" "$pkgmakefile")"

}

main
