#!/usr/bin/env bash
[[ " plugin plugin:install plugin:install-dependencies plugin:update plugin:disable plugin:enable plugin:uninstall help plugin:help " == *" $1 "* ]] || exit $DOKKU_NOT_IMPLEMENTED_EXIT
set -eo pipefail; [[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/plugin/functions"

case "$1" in
  plugin)
    plugn list
    ;;

  plugin:install)
    case "$2" in
      --core)
        [[ "$#" -gt 2 ]] && dokku_log_info1_quiet "Cannot install additional core plugins, running core plugin install trigger"
        PLUGIN_PATH="$PLUGIN_CORE_PATH" plugn trigger install
        ;;
      https:*|git:*|ssh:*)
        PLUGIN_GIT_URL="$2"
        download_and_enable_plugin "$PLUGIN_GIT_URL" "$3"
        plugn trigger install
        ;;
      *)
        plugn trigger install
        ;;
    esac
    ;;

  plugin:install-dependencies)
    if [[ $2 == "--core" ]]; then
      export PLUGIN_PATH="$PLUGIN_CORE_PATH"
    fi
    plugn trigger dependencies
    ;;

  plugin:update)
    case "$2" in
      https:*|git:*)
        PLUGIN_GIT_URL="$2"
        download_and_enable_plugin "$PLUGIN_GIT_URL" "$3"
        plugn trigger update
        ;;
      *)
        plugn trigger update
        ;;
    esac
    ;;

  plugin:disable)
    [[ -z $2 ]] && dokku_log_fail "Please specify a plugin to disable"
    PLUGIN="$2"
    disable_plugin "$PLUGIN"
    ;;

  plugin:enable)
    [[ -z $2 ]] && dokku_log_fail "Please specify a plugin to enable"
    PLUGIN="$2"
    enable_plugin "$PLUGIN"
    ;;

  plugin:uninstall)
    [[ -z $2 ]] && dokku_log_fail "Please specify a plugin to enable"
    PLUGIN="$2"
    uninstall_plugin "$PLUGIN"
    ;;

  help | plugin:help)
    cat<<EOF
    plugin, Print active plugins
    plugin:install [--core|git-url], Optionally download git-url & run install trigger for active plugins (or only core ones)
    plugin:install-dependencies [--core], Run install-dependencies trigger for active plugins (or only core ones)
    plugin:update [git-url], Optionally download git-url & run update trigger for active plugins
    plugin:enable <name>, Enable a previously disabled plugin
    plugin:disable <name>, Disable an installed plugin (third-party only)
    plugin:uninstall <name>, Uninstall a plugin (third-party only)
EOF
    ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
    ;;

esac


