#!/usr/bin/env bash
[[ " domains domains:setup domains:add domains:clear domains:remove domains:disable domains:enable domains:set-global help domains: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/domains/functions"
source "$PLUGIN_AVAILABLE_PATH/nginx-vhosts/functions"

case "$1" in
  domains)
    domains_main "$2"
    ;;

  domains:setup)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
    domains_setup "$2"
    ;;

  domains:add)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"

    if [[ -z "${*:3}" ]]; then
      echo "Usage: dokku $1 $2 DOMAIN [DOMAIN ...]"
      echo "Must specify DOMAIN."
      exit 1
    fi
    shift 1
    domains_add "$@"
    ;;

  domains:clear)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
    domains_clear "$2"
    ;;

  domains:remove)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"

    if [[ -z "${*:3}" ]]; then
      echo "Usage: dokku $1 $2 DOMAIN [DOMAIN ...]"
      echo "Must specify DOMAIN."
      exit 1
    fi

    shift 1
    domains_remove "$@"
    ;;

  domains:disable)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
    domains_disable "$2"
    ;;

  domains:enable)
    [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
    domains_enable "$2"
    ;;

  domains:set-global)
    [[ -z $2 ]] && dokku_log_fail "Please specify a global domain name"
    domains_set_global "$2"
    ;;

  help | domains:help)
    cat<<EOF
    domains [<app>], List domains
    domains:add <app> DOMAIN, Add a domain to app
    domains:clear <app>, Clear all domains for app
    domains:disable <app>, Disable VHOST support
    domains:enable <app>, Enable VHOST support
    domains:remove <app> DOMAIN, Remove a domain from app
    domains:set-global <domain>, Set global domain name
EOF
    ;;

  *)
    exit "$DOKKU_NOT_IMPLEMENTED_EXIT"
    ;;

esac
