set -e

VERSION=0.1.0

main() {
  command=              # Subrepo subcommand to run
  command_arguments=""  # Command args after getopt parsing
  # subrepos=""           # List of multiple subrepos
  quiet_wanted=false    # Output should be quiet
  verbose_wanted=false  # Output should be verbose
  # all_wanted=false      # Apply command to all subrepos

  OK=true               # Flag that commands have succeeded
  FAIL=true             # Flag for RUN: fail on error
  OUT=false             # Flag for RUN: put output in $output
  SAY=true              # Flag for RUN: print command for verbose
}

# shellcheck disable=SC2034
get_command_options() {
  [ "$#" -eq 0 ] && set -- --help

  [ -n "${cmd_DEBUG}" ] && set -x
  [ -n "${cmd_QUIET}" ] && quiet_wanted=true
  [ -n "${cmd_VERBOSE}" ] && verbose_wanted=true

  eval "$(echo "${usage-}" | git rev-parse --parseopt -- "$@" \
    || echo exit "$?")"

  while [ $# -gt 0 ]; do
    option="$1"
    shift
    case "${option}" in
      --) break ;;
      -b) subrepo_branch="$1"
          override_branch="$1"
          shift ;;
      -r) subrepo_remote="$1"
          override_remote="$1"
          shift ;;
      -u) update_wanted=true ;;
      -q) quiet_wanted=true ;;
      -v) verbose_wanted=true ;;
      -x) set -x ;;
      --version)
        echo "${VERSION}"
        exit ;;
      *) error "unexpected option: ${option}" ;;
    esac
  done

  command="$1"
  shift
  command_arguments="${command_arguments}$@"
}

# Smart command runner
RUN() {
  ${verbose_wanted} && ${SAY} && say '>>>' "$*"

  OK=true
  set +e
  if ${verbose_wanted}; then
    out="$("$@")"
  else
    if ${OUT}; then
      out="$("$@" 2>/dev/null)"
    else
      out="$("$@" 2>&1)"
    fi
  fi
  rc="$?"
  set -e

  if [ -z "${rc}" ]; then
    OK=false
    ${FAIL} && error "command failed: $*"
  fi
  if ${OUT}; then
    output="${out}"
  fi
}

# Print unless quiet mode:
say() {
  ${quiet_wanted} || echo "$@"
}

# Print to stderr:
err() {
  echo "$@" >&2
}

# Check if OK:
OK() {
  ${OK}
}

# Nicely report common error messages:
error() {
  msg=
  printf -v msg "Error: %s\n" "$1"
  die "${msg}"
}

# Start at the end:
[ "${BASH_SOURCE}" = "$0" ] && main "$@"

true
