#! /usr/bin/env bash

# Copyright 2020, Mark Callow
# SPDX-License-Identifier: Apache-2.0

# Script to generate version number files using the output of git
# describe.

# A file of this name will be created in the subdir (object) for which a
# version number is being generated.
VF=version.h
DEF_VER=v5.0

LF='
'

# git describe has to be run in the Git repo root.
# Before changing the directory to the repo root capture
# the working directory to support <object> values that are
# relative paths. This is particularly helpful for CMake
# sub-projects in subdirectories of the repo.
depth=..
workdir=$(pwd)
cd $(dirname $0)/$depth

if which cygpath > /dev/null ; then
  # In GHA Windows runner image version 20260428.110.2, the pwd
  # call to set workdir sometimes returns a Windows style path
  # which causes the RE near the end of the script to find no
  # match. Instead of spending time investigating what has been
  # broken and where, if cygpath exists use it to ensure a unix
  # style path.
  workdir=$(cygpath -u $workdir)

  # More details.
  #
  # In GHA runners cmake always finds the Git 4 Windows bash, which is
  # the MinGW version originating from cygwin. The broken runner image
  # has bash 5.3.9(1)-release and Git 4 Windows 2.54. The call that
  # has the problem is
  #
  # C:\Windows\system32\cmd.exe /C "cd /D D:\a\KTX-Software\KTX-Software && "C:\Program Files\Git\bin\bash.exe" -- D:/a/KTX-Software/KTX-Software/cmake/../scripts/mkversion -o version.h tools/ktx"
  #
  # A, presumably, similar call earlier in the build with a current
  # directory of D:\...KTX-Software\lib and a target of src does not
  # have this problem. I say presumably because since the call works
  # the log does not show the actual command.
  #
  # I have been unable to reproduce the problem on my Windows system
  # having the same versions of bash and Git 4 Windows.
fi

# `man 7 gitrevisions` for the meaning of the output from git describe.
function genversion() {
  # Try git-describe, then default.
  if [ -d ${GIT_DIR:-.git} -o -f .git ]; then
    if [ -z "$1" ]; then
      # Get version number for HEAD revision of repo.
      VN=$(git describe --match "v[0-9]*" HEAD 2>/dev/null)
    else
      # Get release tag containing the object identified in # $1.
      VN=$(git describe --contains --match "v[0-9]*" --exclude "*-beta*" --exclude "*-rc[0-9]*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      if [ -z "$VN" ]; then
        # No containing release tag. Look for an RC tag.
        VN=$(git describe --contains --match "v[0-9]*" --exclude "*-beta*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      fi
      if [ -z "$VN" ]; then
        # No containing RC tag. Look for a beta tag.
        VN=$(git describe --contains --match "v[0-9]*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      fi
      if [ -z "$VN" ]; then
        # No containing tag. Get version number a previous tag.
        VN=$(git describe --match "v[0-9]*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      fi
      if [ -z "$VN" ]; then
        # No tags at all, best we can do is tag the commit.
        VN="$DEF_VER-$(git rev-parse --short HEAD 2>/dev/null)"
      fi
    fi
    case "$VN" in
    *$LF*) (exit 1) ;;
    v[0-9]*)
        git update-index -q --refresh
        test -z "$(git diff-index --name-only HEAD --)" ||
        VN="$VN-dirty" ;;
    esac
  else
      VN="$DEF_VER"
  fi
}

# Write the version file, if the new version is different than the
# existing one.
function setfile() {
  local VC
  local verstring=$1_VERSION
  if [ $dry_run -eq 1 ]; then
    echo $verstring $VN
    if [ -n $VF ]; then
      echo "will be written to $2"
    fi
    return
  fi
  if [ -r $2 ]; then
    VC=$(grep $verstring $2 | sed -e "s/^#define $verstring //")
  else
    VC=unset
  fi
  if [ $force -eq 1 -o "$VN" != "$VC" ]; then
    echo "/*" > $2
    if [ "$1" = "LIBKTX" ]; then
      (echo "// [API version]"
      echo "@par API Version"
      echo "$DEF_VER"
      echo "// [API version]") >> $2
    fi
    (echo "// [Code version]"
    echo "$VN"
    echo "// [Code version]"
    echo "*/"
    echo "#define $verstring $VN"
    echo "#define $1_DEFAULT_VERSION $DEF_VER.__default__") >> $2
  fi
}

# Figure out the object name and write its version file.
function writeversion() {
  # Extract version from git if it is not passed via command line
  if [ -z "$VN" ]; then
    genversion $1
  fi
  local vfp;
  if [ -z "$1" ]; then
    vfp=$VF
  else
    vfp=$1/$VF
  fi
  if [[ $1 =~ .*lib$ || $1 =~ .*lib/src$ ]]; then
    ON=LIBKTX
    setfile $ON $1/$VF
  elif [ "$OBJ" == "." ]; then
    # Will only get "." if in repo root.
    ON=KTX-Software
    setfile $ON $1
  else
    ON=$(basename $1)
    ON=$(echo $ON | tr [:lower:] [:upper:])
    setfile $ON $1/$VF
  fi
}

function usage() {
    echo "Usage: $0 [-a] [-f] [-n] [-v version] [-o <outfile>] [<object>]"
    exit 1
}

force=0
dry_run=0
write_all=0;
args=$(getopt afnv:o: $*)

set -- $args
for i; do
  case "$i" in
    -a) write_all=1;
        shift;;
    -f) force=1;
        shift;;
    -n) dry_run=1;
        shift;;
    -v) VN=$2; shift; shift;;
    -o) VF=$2; shift; shift;;
    --) shift; break;;
  esac
done

case $# in
  0) if [ $write_all -ne 1 ]; then usage; fi;;
  1) OBJ=$1;;
  2) usage;;
esac

if [ $write_all -eq 1 ]; then
  for i in lib lib/src tools/*; do
    if [ -d $i -a "$i" != "tools/package" ]; then
      writeversion $i
    fi
  done
else
  if [[ $workdir =~ "$(pwd)"(/(.*$)?)? ]]; then
    # Trailing part of workdir gives object location in repo.
    if [ -n "${BASH_REMATCH[2]}" ]; then
      if [ "$OBJ" == "." ]; then
        OBJ=${BASH_REMATCH[2]}
      else
        OBJ=${BASH_REMATCH[2]}/$OBJ
      fi
    # else  We are in the repo root
    fi
  else
      >&2 echo "$0: Working directory is not in KTX-Software repo."
      exit 1
  fi
  writeversion $OBJ
fi

# vim:ai:ts=4:sts=4:sw=2:expandtab:textwidth=70
