#!/bin/sh -e

# Logs an information message (dark gray)
projextCLIInfoLog() {
  echo "\033[90m[projext] $1\033[39m"
}

# Logs a success message (green)
projextCLISuccessLog() {
  echo "\033[32m[projext] $*\033[39m"
}

# Logs a message that indicates a task is starting (yellow)
projextCLIStartTaskLog() {
  echo "\033[33m[projext] $1\033[39m"
}

# Logs a message that indicates a task was completed (green), and replaces the last logged
# message
projextCLICompleteTaskLog() {
  echo "\033[2A";
  printf "\033[0K\r\033[32m[projext] %s\033[39m" "$*"
  echo ""
}

# Get the name of the task to execute
task=$1
# If this flags gets to be true, the execution will be handled by the Node CLI
disableSHTasks=false
# Determine whether the task is a private helper task or not
isSHTask=false
# Whether or not the real bash command will be shown
showSHCommand=false
if echo "$*" | grep -q "\(\s\-\-\(projextdebug\)\(\s\|$\)\)"; then
  showSHCommand=true
fi

# If no task was specified...
if [ "$task" = "" ]; then
  # ...show the Node CLI help information
  projext-cli --help
else
  # ...otherwise, check if the task is a shell task that needs commands
  if echo "$task" | grep -q "^\(build\|run\|watch\|inspect\|analyze\)$"; then
    isSHTask=true
  fi

  # check if the task was used with a 'help' or 'version' option
  if echo "$*" | grep -q "\(\s\-\-\?\(help\|h\|version\|v\)\(\s\|$\)\)"; then
    disableSHTasks=true
  fi

  # If the task is a shell task that needs commands...
  if [ "$isSHTask" = true ] && [ "$disableSHTasks" = false ]; then
      # ... let the user know the CLI started working
      projextCLIInfoLog "> $*"
      # execute a validation command to avoid any error being thrown on the
      # command that returns the list.
      if [ "$showSHCommand" = true ]; then
        echo "> projext-cli sh-validate-$*"
      fi
      projextCLIStartTaskLog "Validating the command"
      eval "projext-cli sh-validate-$*"
      projextCLISuccessLog "Command validated"
      # Capture the commands that need to run
      if [ "$showSHCommand" = true ]; then
        echo "> projext-cli sh-$*"
      fi
      projextCLIStartTaskLog "Loading instructions"
      command=$(eval "projext-cli sh-$*")
      # If there are commands to run...
      if [ "$command" != "" ]; then
        projextCLICompleteTaskLog "Instructions loaded"
        projextCLIInfoLog "Executing instructions"
        # Show the real command(s) if the debug flag was used.
        if [ "$showSHCommand" = true ]; then
          echo "> $command"
        fi
        # ...and execute the commands
        eval "$command"
      fi
  else
    # ...otherwise, delegate everything to the Node CLI
    projext-cli "$@"
  fi
fi
