#!/bin/sh

prog=$(basename "$0")
progname="$0"
# progname=$(basename "$0")
nl='
'
IFS=" ""	${nl}"

email=$(git config get user.email)

# func_usage
# outputs to stdout the --help usage message.
func_usage() {
  printf %s "\
Usage: ${prog} --list
       ${prog} --find filename
       ${prog} --update
       ${prog} --test --dir=directory [module1 ... moduleN]
       ${prog} --extract-description module
       ${prog} --extract-include-directive module
       ${prog} --extract-license module
       ${prog} --extract-maintainer module
       ${prog} --extract-tests-module module
       ${prog} --copy-file file [destination]

Operation modes:

      --list                print the available module names
      --find                find the modules which contain the specified file
      --update              update the current package, restore files omitted
                            from version control
      --test                test the combination of the given modules
                            (recommended to use CC=\"gcc -Wall\" here)
      --extract-description        extract the description
      --extract-include-directive  extract the #include directive
      --extract-license            report the license terms of the source files
                                   under lib/
      --extract-maintainer         report the maintainer(s) inside gnulib
      --extract-tests-module       report the unit test module, if it exists
      --copy-file                  copy a file that is not part of any module
      --help                Show this help text.
      --version             Show version and authorship information.

General options:

      --dir=DIRECTORY       Specify the target directory.
                            For --import, this specifies where your
                            configure.ac can be found.  Defaults to current
                            directory.
      --verbose             Increase verbosity. May be repeated.
      --quiet               Decrease verbosity. May be repeated.

Options for --create-[mega]testdir, --[mega]test:

      --two-configures      Generate a separate configure file for the tests
                            directory, not a single configure file.

Options for --import, --add/remove-import, --update,
            --create-[mega]testdir, --[mega]test:

  -s, --symbolic, --symlink Make symbolic links instead of copying files.
      --local-symlink       Make symbolic links instead of copying files, only
                            for files from the local override directory.
  -h, --hardlink            Make hard links instead of copying files.
      --local-hardlink      Make hard links instead of copying files, only
                            for files from the local override directory.

Report bugs to <${email}>.
"
}

# --version | --versio | --versi | --vers)
#   func_version
#   func_exit "$?"
#   ;;
# func_version
# outputs to stdout the --version message.
# func_version() {
#   func_lib_dir
#   if test -d "${lib_dir}"/.git \
#     && (git --version) >/dev/null 2>/dev/null \
#     && (date --version) >/dev/null 2>/dev/null; then
#     # gnulib checked out from git.
#     sed_extract_first_date='/^Date/{
# s/^Date:[	 ]*//p
# q
# }'
#     date=$(cd "${lib_dir}" && git log -n 1 --format=medium --date=iso ChangeLog | sed -n -e "${sed_extract_first_date}")
#     # Use GNU date to compute the time in GMT.
#     date=$(date -d "${date}" -u +"%Y-%m-%d %H:%M:%S")
#     version=' '$(cd "${lib_dir}" && ./build-aux/git-version-gen /dev/null | sed -e 's/-dirty/-modified/')
#   else
#     # gnulib copy without versioning information.
#     date=$(sed -e 's/ .*//;q' "${lib_dir}"/ChangeLog)
#     version=
#   fi
#   year=$("${lib_dir}"/build-aux/mdate-sh "${self_abspathname}" | sed -e 's,^.* ,,')
#   echo "\
# gnulib-tool (GNU ${package-} ${date})${version}
# Copyright (C) ${year} Free Software Foundation, Inc.
# License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
# "
#   printf "Written by %s.\n" "${LOGNAME:-${USER}}"
# }

# func_exit STATUS
# exits with a given status.
# This function needs to be used, rather than 'exit', when a 'trap' handler is
# in effect that refers to $?.
func_exit() {
  (exit "$1")
  exit "$1"
}

# func_fatal_error message
# outputs to stderr a fatal error message, and terminates the program.
# Input:
# - progname                 name of this program
func_fatal_error() {
  echo "${progname}: *** $1" 1>&2
  echo "${progname}: *** Stop." 1>&2
  func_exit 1
}

# func_warning message
# Outputs to stderr a warning message,
func_warning() {
  echo "${progname}: warning: $1" 1>&2
}

# func_readlink SYMLINK
# outputs the target of the given symlink.
if (type readlink) >/dev/null 2>&1; then
  func_readlink() {
    # Use the readlink program from GNU coreutils.
    readlink "$1"
  }
else
  func_readlink() {
    # Use two sed invocations. A single sed -n -e 's,^.* -> \(.*\)$,\1,p'
    # would do the wrong thing if the link target contains " -> ".
    # shellcheck disable=SC2012
    LC_ALL=C ls -l "$1" | sed -e 's, -> ,#%%#,' | sed -n -e 's,^.*#%%#\(.*\)$,\1,p'
  }
fi

# func_lib_dir
# locates the directory where the gnulib repository lives
# Input:
# - progname                 name of this program
# Sets variables
# - self_abspathname         absolute pathname of lib-tool
# - lib_dir                  absolute pathname of lib repository
func_lib_dir() {
  # shellcheck disable=SC2250
  case "${progname}" in
    /* | ?:*) self_abspathname="${progname}" ;;
    */*) self_abspathname=$(pwd)/"${progname}" ;;
    *)
      # Look in $PATH.
      # Iterate through the elements of $PATH.
      # We use IFS=: instead of
      #   for d in `echo ":$PATH:" | sed -e 's/:::*/:.:/g' | sed -e 's/:/ /g'`
      # because the latter does not work when some PATH element contains spaces.
      # We use a canonicalized $pathx instead of $PATH, because empty PATH
      # elements are by definition equivalent to '.', however field splitting
      # according to IFS=: loses empty fields in many shells:
      #   - /bin/sh on Solaris loses all empty fields (at the beginning, at
      #     the end, and in the middle),
      #   - GNU bash, /bin/sh on AIX and HP-UX, and /bin/ksh on AIX, HP-UX,
      #     Solaris lose empty fields at the end.
      # The 'case' statement is an optimization, to avoid evaluating the
      # explicit canonicalization command when $PATH contains no empty fields.
      self_abspathname=
      if test "${PATH_SEPARATOR}" = ";"; then
        # On Windows, programs are searched in "." before $PATH.
        pathx=".;$PATH"
      else
        # On Unix, we have to convert empty PATH elements to ".".
        pathx="$PATH"
        # shellcheck disable=SC2249
        case :$PATH: in
          *::*)
            pathx=$(echo ":$PATH:" | sed -e 's/:::*/:.:/g' -e 's/^://' -e 's/:\$//')
            ;;
        esac
      fi
      saved_IFS="${IFS}"
      IFS="${PATH_SEPARATOR}"
      for d in ${pathx}; do
        IFS="${saved_IFS}"
        test -z "${d}" && d=.
        if test -x "${d}/${progname}" && test ! -d "${d}/${progname}"; then
          self_abspathname="${d}/${progname}"
          break
        fi
      done
      IFS="${saved_IFS}"
      if test -z "${self_abspathname}"; then
        func_fatal_error "could not locate ${progname} program - how did you invoke it?"
      fi
      ;;
  esac
  while test -h "${self_abspathname}"; do
    # Resolve symbolic link.
    linkval=$(func_readlink "${self_abspathname}")
    test -n "${linkval}" || break
    case "${linkval}" in
      /* | ?:*) self_abspathname="${linkval}" ;;
      *) self_abspathname=$(echo "${self_abspathname}" | sed -e 's,/[^/]*$,,')/"${linkval}" ;;
    esac
  done
  lib_dir=$(echo "${self_abspathname}" | sed -e 's,/[^/]*$,,')
}

# Determine whether we should use ':' or ';' as PATH_SEPARATOR.
func_determine_path_separator() {
  # shellcheck disable=SC2250,SC2034
  if test "${PATH_SEPARATOR+set}" != set; then
    # Determine PATH_SEPARATOR by trying to find /bin/sh in a PATH which
    # contains only /bin. Note that ksh looks also at the FPATH variable,
    # so we have to set that as well for the test.
    PATH_SEPARATOR=:
    (
      PATH='/bin;/bin'
      FPATH=$PATH
      sh -c :
    ) >/dev/null 2>&1 \
      && {
        (
          PATH='/bin:/bin'
          FPATH=$PATH
          sh -c :
        ) >/dev/null 2>&1 \
          || PATH_SEPARATOR=';'
      }
  fi
}

# func_tmpdir
# creates a temporary directory.
# Input:
# - progname                 name of this program
# Sets variable
# - tmp             pathname of freshly created temporary directory
# shellcheck disable=SC2250,SC3028
func_tmpdir() {
  # Use the environment variable TMPDIR, falling back to /tmp. This allows
  # users to specify a different temporary directory, for example, if their
  # /tmp is filled up or too small.
  : "${TMPDIR=/tmp}"
  {
    # Use the mktemp program if available. If not available, hide the error
    # message.
    tmp=$( (umask 077 && mktemp -d "${TMPDIR}/${progname}XXXXXX") 2>/dev/null) \
      && test -n "${tmp}" && test -d "${tmp}"
  } \
    || {
      # Use a simple mkdir command. It is guaranteed to fail if the directory
      # already exists.  $RANDOM is bash specific and expands to empty in shells
      # other than bash, ksh and zsh.  Its use does not increase security;
      # rather, it minimizes the probability of failure in a very cluttered /tmp
      # directory.
      tmp=${TMPDIR}/gl$$-$RANDOM
      (umask 077 && mkdir "${tmp}")
    } \
    || {
      echo "${progname}: cannot create a temporary directory in ${TMPDIR}" >&2
      func_exit 1
    }
}

func_lib_dir
func_tmpdir
# shellcheck disable=SC2154
trap 'exit_status=$?
      if test "$signal" != EXIT; then
        echo "caught signal SIG$signal" >&2
      fi
      rm -rf "$tmp"
      exit $exit_status' EXIT
for signal in HUP INT QUIT PIPE TERM; do
  trap '{ signal='"${signal}"'; func_exit 1; }' "${signal}"
done
signal=EXIT

# unset CDPATH. otherwise, output from 'cd dir' can cause trouble.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH

# Determine the path separator early because the following option parsing code
# requires that.
func_determine_path_separator

# func_execute_command command [args...]
# Executes a command.
# Uses also the variables
# - verbose         integer, default 0, inc/decremented by --verbose/--quiet
func_execute_command() {
  if test "${verbose}" -ge 0; then
    echo "executing $*"
    "$@"
  else
    # Commands like automake produce output to stderr even when they succeed.
    # Turn this output off if the command succeeds.
    "$@" >"${tmp}"/cmdout 2>&1
    cmdret="$?"
    if test "${cmdret}" = 0; then
      rm -f "${tmp}"/cmdout
    else
      echo "executing $*"
      cat "${tmp}"/cmdout 1>&2
      rm -f "${tmp}"/cmdout
      (exit "${cmdret}")
    fi
  fi
}

mode=
verbose=0
doit=:

while test "$#" -gt 0; do
  case "$1" in
    --list | --lis)
      mode=list
      shift
      ;;
    --find | --fin | --fi | --f)
      mode=find
      shift
      ;;
    --verbose | --verbos | --verbo | --verb)
      verbose=$((verbose + 1))
      shift
      ;;
    --quiet | --quie | --qui | --qu | --q)
      verbose=$((verbose - 1))
      shift
      ;;
    --dry-run)
      doit=false
      shift
      ;;
    --help | --hel | --he)
      func_usage
      func_exit "$?"
      ;;
    --)
      # Stop option processing
      shift
      break
      ;;
    -*)
      echo "${progname}: unknown option $1" 1>&2
      echo "Try '${progname} --help' for more information." 1>&2
      func_exit 1
      ;;
    *)
      break
      ;;
  esac
done

rm -rf "${tmp}"
# Undo the effect of the previous 'trap' command. Some shellology:
# We cannot use "trap - EXIT HUP INT QUIT PIPE TERM", because Solaris sh would
# attempt to execute the command "-". "trap '' ..." is fine only for signal EXIT
# (= normal exit); for the others we need to call 'exit' explicitly. The value
# of $? is 128 + signal number and is set before the trap-registered command is
# run.
trap '' EXIT
trap 'func_exit $?' HUP INT QUIT PIPE TERM

exit 0
