#!/usr/bin/sh
# Generate the header file for including git repository HEAD information.

OUTPUT="$1"
WORK_TREE="$2"

GIT="${GIT:-$(command -v git 2>/dev/null)}"
XSUM="${XSUM:-$(command -v md5sum 2>/dev/null)}"
XSUM="${XSUM:-$(command -v cksum 2>/dev/null)}" # fallback

GIT_HASH=""
GIT_DATE=""
GIT_DIRTY=0

if test -x "${GIT}" ; then
  # Set working directory by -C to execute git commands in source directory.
  GIT_HASH="$(LANG=C ${GIT} -C "${WORK_TREE}" log --pretty=format:%h --abbrev=10 -n 1 2>git-error.log)"
  GIT_DATE="$(LANG=C ${GIT} -C "${WORK_TREE}" log --pretty=format:%ad --date=format:%Y%m%d -n 1 2>/dev/null)"
  GIT_STATUS="$(LANG=C ${GIT} -C "${WORK_TREE}" status -uno -s 2>/dev/null | head -n 1)"

  if test -n "${GIT_HASH}" ; then
    echo "INFO: GIT Hash = \"${GIT_HASH}\""
  fi
  if test -n "${GIT_DATE}" ; then
    echo "INFO: GIT Date = \"${GIT_DATE}\""
  fi
  if test -n "${GIT_STATUS}" ; then
    echo "INFO: GIT There are changes not committed yet."
    GIT_DIRTY=1
  fi
fi
if test -f git-error.log ; then
  # Reject to run git on unowned repository since CVE-2022-24765 fix.
  if grep -F "add safe.directory" git-error.log 1>/dev/null 2>&1 ; then
    cat git-error.log
    rm git-error.log
    echo ""
    if test -f "${OUTPUT}" ; then
      echo "NOTE: Continue processing using the previously generated buildinfo.h."
      echo "See https://github.com/JDimproved/JDim/issues/965"
      exit 0
    else
      echo "ERROR: Stop processing due to missing the buildinfo.h."
      echo "See https://github.com/JDimproved/JDim/issues/965"
      exit 1
    fi
  fi
  # If other error occured or successful, continue processing.
  rm git-error.log
fi

(
echo "/*"
echo " * Autogenerated by the Meson build system."
echo " * Do not edit, your changes will be lost."
echo " */"
echo ""
echo "#pragma once"
echo ""
echo "#define GIT_HASH \"${GIT_HASH}\""
echo "#define GIT_DATE \"${GIT_DATE}\""
echo "#define GIT_DIRTY ${GIT_DIRTY}"
) > "${OUTPUT}.new"

if test ! -f "${OUTPUT}" ; then
  mv "${OUTPUT}.new" "${OUTPUT}"
  echo "INFO: ${OUTPUT} is created."
elif test ! -x "${XSUM}" ; then
  mv "${OUTPUT}.new" "${OUTPUT}"
  echo "INFO: ${OUTPUT} is refreshed."
else
  # Compare file hashes to check update need.
  HASH1="$("${XSUM}" < "${OUTPUT}")"
  HASH2="$("${XSUM}" < "${OUTPUT}.new")"
  if test "${HASH1}" = "${HASH2}" ; then
    rm "${OUTPUT}.new"
    echo "INFO: ${OUTPUT} is not modified."
  else
    mv "${OUTPUT}.new" "${OUTPUT}"
    echo "INFO: ${OUTPUT} is modified."
  fi
fi
