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

disable_plugin() {
  declare desc="disables specified plugin name"
  local PLUGIN="$1"
  [[ -e $PLUGIN_CORE_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Cannot disable a core plugin"
  [[ ! -e $PLUGIN_ENABLED_PATH/$PLUGIN ]] && dokku_log_fail "Plugin already disabled"
  [[ ! -e $PLUGIN_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Plugin does not exist"
  plugn disable "$PLUGIN"
  dokku_log_info1_quiet "Plugin $PLUGIN disabled"
}

enable_plugin() {
  declare desc="enables specified plugin name"
  local PLUGIN="$1"
  [[ -e $PLUGIN_ENABLED_PATH/$PLUGIN ]] && dokku_log_fail "Plugin already enabled"
  [[ ! -e $PLUGIN_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Plugin does not exist"
  plugn enable "$PLUGIN"
  dokku_log_info1_quiet "Plugin $PLUGIN enabled"
}

download_plugin() {
  declare desc="download plugin from URL and set name"
  local PLUGIN_GIT_URL="$1"
  local PLUGIN_NAME="$2"
  plugn install "$PLUGIN_GIT_URL" "$PLUGIN_NAME"
}

download_and_enable_plugin() {
  declare desc="wrapper to download and enable specified version of plugin"
  local PLUGIN_GIT_URL="$1"
  shift
  local SKIP_INSTALL_TRIGGER=false
  while getopts ":-:" opt "$@"; do
    case "$opt" in
      -)
        case "$OPTARG" in
          committish)
            val="${!OPTIND}"
            OPTIND=$((OPTIND + 1))
            local PLUGIN_COMMITTISH="$val"
            ;;
          name)
            val="${!OPTIND}"
            OPTIND=$((OPTIND + 1))
            local CUSTOM_NAME="$val"
            ;;
          skip-install-trigger)
            SKIP_INSTALL_TRIGGER=true
            ;;
        esac
        ;;
    esac
  done
  local PLUGIN_NAME=${CUSTOM_NAME:-$(plugin_name "$PLUGIN_GIT_URL")}
  dokku_log_info1_quiet "Cloning plugin repo $PLUGIN_GIT_URL to $PLUGIN_AVAILABLE_PATH/$PLUGIN_NAME"
  download_plugin "$PLUGIN_GIT_URL" "$PLUGIN_NAME"
  enable_plugin "$PLUGIN_NAME"
  if [[ -n "$PLUGIN_COMMITTISH" ]]; then
    update_plugin "$PLUGIN_NAME" "$PLUGIN_COMMITTISH"
  fi
  if [[ "$SKIP_INSTALL_TRIGGER" == "false" ]]; then
    plugn trigger install
  fi
}

update_plugin() {
  declare desc="update plugin"
  local PLUGIN="$1"
  local PLUGIN_COMMITTISH="$2"
  [[ ! -e $PLUGIN_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Plugin ($PLUGIN) is not currently installed"
  plugn update "$@"
}

uninstall_plugin() {
  declare desc="uninstall plugin"
  local PLUGIN="$1"
  [[ -e $PLUGIN_CORE_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Cannot uninstall a core plugin"
  [[ ! -e $PLUGIN_AVAILABLE_PATH/$PLUGIN ]] && dokku_log_fail "Plugin ($PLUGIN) is not currently installed"
  plugn trigger uninstall "$PLUGIN"
  plugn uninstall "$PLUGIN"
  dokku_log_info1_quiet "Plugin $PLUGIN uninstalled"
}

plugin_name() {
  declare desc="default plugin name"
  local PLUGIN_GIT_URL="$1"
  echo "$PLUGIN_GIT_URL" | awk -F '/' '{ print $NF }' | sed -e "s:.git$::g" | sed 's:^dokku-::'
}
