#!/usr/bin/env bash
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_PATH/common/functions"

config_export() {
  local CONFIG_TYPE="$1"
  local APP="$2"
  local ENV_FILE="$DOKKU_ROOT/$APP/ENV"

  [[ $CONFIG_TYPE == "global" ]] && ENV_FILE="$DOKKU_ROOT/ENV"
  [[ ! -f $ENV_FILE ]] && return 0
  [[ ! -s $ENV_FILE ]] && return 0

  VARS=$(grep -Eo "export ([a-zA-Z_][a-zA-Z0-9_]*=.*)" $ENV_FILE | cut -d" " -f2-)
  echo "$VARS" | awk '{print "export " $0}'
  return 0
}

config_parse_args() {
  case "$2" in
    --global)
      ENV_FILE="$DOKKU_ROOT/ENV"
      DOKKU_CONFIG_TYPE="global"
      DOKKU_CONFIG_RESTART=false
      ;;
    --no-restart)
      APP="$3"
      ENV_FILE="$DOKKU_ROOT/$APP/ENV"
      DOKKU_CONFIG_RESTART=false
      DOKKU_CONFIG_TYPE="app"
      set -- "${@:1:1}" "${@:3}"
  esac

  APP=${APP:="$2"}
  ENV_FILE=${ENV_FILE:="$DOKKU_ROOT/$APP/ENV"}
  DOKKU_CONFIG_TYPE=${DOKKU_CONFIG_TYPE:="app"}
  DOKKU_CONFIG_RESTART=${DOKKU_CONFIG_RESTART:=true}

  if [[ "$DOKKU_CONFIG_TYPE" = "app" ]]; then
    if [[ -z $APP ]]; then
      echo "Please specify an app to run the command on" >&2 && exit 1
    else
      verify_app_name "$2"
    fi
  fi
  export APP ENV_FILE DOKKU_CONFIG_TYPE DOKKU_CONFIG_RESTART
}
