#!/bin/sh
DAT_ROOT="/var/lib/lua/"
DAT_MASTER="lua"
DAT_CHOICE="/usr/bin/lua5.4"
DAT_BASE="lua5.4"

#!/bin/sh
################################################################
# __check_cygwin_env ():
#   a function to extract the last setting of a specified
#   option in CYGWIN variable.
#
#   Usage: __check_cygwin_env option_name
#
#   cf. The Cygwin User's Guide: The CYGWIN environment variable [1].
#   [1]: https://cygwin.com/cygwin-ug-net/using-cygwinenv.html
#
__check_cygwin_env () {
  X_R=''
  X_C=`printf "%s" "$1" | sed -e 's/^no//'`        # Remove a prefix 'no'
  for X_OPT in ${CYGWIN}; do
    X_T="${X_OPT}"
    X_T=`printf "%s" "${X_T}" | sed -e 's/^no//'`  # Remove a prefix 'no'
    X_T=`printf "%s" "${X_T}" | sed -e 's/:.*$//'` # Remove optional parameters
    if [ x"${X_T}" = x"${X_C}" ]; then
      X_R="${X_OPT}"
    fi
  done
  printf "%s" "${X_R}"
}

################################################################
# A workaround when CYGWIN variable has 'winsymlinks:nativestrict'
#
if [ x"winsymlinks:nativestrict" = x"`__check_cygwin_env winsymlinks`" ]; then
  echo "$0: *** WARNING ***"
  echo "  CYGWIN variable has 'winsymlinks:nativestrict'..."
  echo "  We are overriding it by 'winsymlinks:native' in this script"
  export CYGWIN="${CYGWIN} winsymlinks:native"
fi

################################################################
DAT_ROOT="${DAT_ROOT}"
DAT_MASTER="${DAT_MASTER}"
DAT_CHOICE="${DAT_CHOICE}"
DAT_BASE="${DAT_BASE}"
DAT_FILE="${DAT_BASE}"

__dat_catenate () {
  cat "${DAT_ROOT}${DAT_BASE}.dat"
  find "${DAT_ROOT}" -name "${DAT_BASE}_*.dat" -print0 \
  | xargs -r -0 cat --
}
__dat_remove () {
  rm -f "${DAT_ROOT}${DAT_FILE}.dat"
  rmdir --ignore-fail-on-non-empty "${DAT_ROOT}"
}
__dat_alternatives () {
  if [ -f "${DAT_ROOT}${DAT_BASE}.dat" ]; then
    __dat_catenate | sh
    /usr/sbin/alternatives --verbose --display "${DAT_MASTER}"
  elif [ x"${DAT_FILE}" = x"${DAT_BASE}" ]; then
    cat <<__EOF
$0:
  alternatives removing a path '${DAT_CHOICE}' from '${DAT_MASTER}'...
__EOF
    /usr/sbin/alternatives \
    --remove "${DAT_MASTER}" "${DAT_CHOICE}" \
    && echo "  ok" || echo "  FAILED"
  fi
}
mkdir -p "${DAT_ROOT}"
cat <<__EOF > "${DAT_ROOT}${DAT_FILE}.dat"
LUA_VERSION=5.4
LUA_VERSION_NUM=504
/usr/sbin/alternatives \\
--install /usr/bin/lua lua /usr/bin/lua\${LUA_VERSION} \${LUA_VERSION_NUM} \\
--slave /usr/bin/luac luac /usr/bin/luac\${LUA_VERSION} \\
--slave /usr/share/man/man1/lua.1.gz lua.1.gz /usr/share/man/man1/lua\${LUA_VERSION}.1.gz \\
--slave /usr/share/man/man1/luac.1.gz luac.1.gz /usr/share/man/man1/luac\${LUA_VERSION}.1.gz \\
__EOF
__dat_alternatives
