#!/bin/bash

# enable debug mode
if [ "$DEBUG" = "yes" ]; then
  set -x
fi

GITNOW_DIR=$0
GITNOW_DIR=${GITNOW_DIR%\\*} # for msysGit
GITNOW_DIR=${GITNOW_DIR%/*}  # for others
export GITNOW_DIR

prefix_config=`git config now.prefix`
if [ $? -eq 0 ]; then
  PREFIX=$prefix_config
else
  PREFIX="from now"
fi

bracket_config=`git config now.bracket`
if [ $? -eq 0 ]; then
  BRACKET=$bracket_config
else
  BRACKET=true
fi

usage() {
  echo "usage: git now [-n] [-v] [--force | -f] [--interactive | -i] [--patch | -p]"
  echo "               [--edit | -e] [--all | [--update | -u]] [--intent-to-add | -N]"
  echo "               [--refresh] [--ignore-errors] [--ignore-missing] [--]"
  echo "               [<filepattern>...]"
  echo
  echo "       git now <subcommand>"
  echo
  echo "Available subcommands are:"
  echo "   add       default subcommand."
  echo "   rebase    rebase for temporary commits."
  echo "   push      remove remote branch before push to remote repoistory for rebase commits."
  echo "   grep      grep temporary commits."
  echo
  echo "Try 'git now <subcommand> help' for details."
}

main() {
  # load common functionality
  . "$GITNOW_DIR/gitnow-common"

  # This environmental variable fixes non-POSIX getopt style argument
  # parsing, effectively breaking git-now subcommand parsing on several
  # Linux platforms.
  export POSIXLY_CORRECT=1

  # use the shFlags project to parse the command line arguments
  . "$GITNOW_DIR/gitnow-shFlags"

  SUBCOMMAND="$1"
  if [ ! -e "$GITNOW_DIR/git-now-$SUBCOMMAND" ]; then
    if [ "$SUBCOMMAND" = "help" ]; then
      usage
      exit 0
    else
      SUBCOMMAND="add"
    fi
  else
    FLAGS_PARENT="git now"
    FLAGS "$@" || exit $?
    eval set -- "${FLAGS_ARGV}"; shift

    FLAGS_PARENT="git now $SUBCOMMAND"
  fi

  # run command
  . "$GITNOW_DIR/git-now-$SUBCOMMAND"

  # test if the first argument is a flag (i.e. starts with '-')
  # in that case, we interpret this arg as a flag for the default
  # command
  SUBACTION="default"
  if [ "$1" = "help" ] && { ! echo "$1" | grep -q "^-"; } then
    SUBACTION="$1"; shift
  fi
  #if ! type "cmd_$SUBACTION" >/dev/null 2>&1; then
  #warn "Unknown subcommand: '$SUBACTION'"
  #usage
  #exit 1
  #fi

  # run the specified action
  cmd_$SUBACTION "$@"
}

main "$@"
