#!/usr/bin/env bash
[[ " nginx:build-config nginx:access-logs nginx:error-logs nginx:disable nginx:enable help nginx: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/config/functions"
source "$PLUGIN_AVAILABLE_PATH/nginx-vhosts/functions"

case "$1" in
  nginx:build-config)
    APP="$2"; DOKKU_APP_LISTEN_PORT="$3"; DOKKU_APP_LISTEN_IP="$4"

    nginx_build_config $APP $DOKKU_APP_LISTEN_PORT $DOKKU_APP_LISTEN_IP

  ;;

  nginx:access-logs|nginx:error-logs)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    verify_app_name "$2"
    APP="$2"

    NGINX_LOGS_TYPE=${1#nginx:}
    NGINX_LOGS_TYPE=${NGINX_LOGS_TYPE%-logs}
    NGINX_LOGS_PATH="/var/log/nginx/$APP-$NGINX_LOGS_TYPE.log"

    if [[ $3 == "-t" ]]; then
      NGINX_LOGS_ARGS="-F"
    else
      NGINX_LOGS_ARGS="-n 20"
    fi

    tail "$NGINX_LOGS_ARGS" "$NGINX_LOGS_PATH"
  ;;

  nginx:disable)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    verify_app_name "$2"
    APP="$2"

    if [[ "$(is_app_vhost_enabled $APP)" == "true" ]]; then
      config_set --no-restart $APP DOKKU_NO_NGINX=1
      disable_app_vhost $APP
    elif [[ "$(is_app_nginx_enabled $APP)" == "true" ]]; then
      config_set --no-restart $APP DOKKU_NO_NGINX=1
      nginx_build_config $APP
    else
      dokku_log_info1 "nginx is already disable for app ($APP)"
    fi
  ;;

  nginx:enable)
    [[ -z $2 ]] && echo "Please specify an app to run the command on" && exit 1
    verify_app_name "$2"
    APP="$2"

    if [[ "$(is_app_nginx_enabled $APP)" == "false" ]]; then
      config_unset --no-restart $APP DOKKU_NO_NGINX NO_VHOST
      unset DOKKU_NO_NGINX NO_VHOST
      nginx_build_config $APP
    else
      dokku_log_info1 "nginx is already enabled for app ($APP)"
    fi
  ;;

  help | nginx:help)
    cat<<EOF
    nginx:build-config <app>, (Re)builds nginx config for given app
    nginx:access-logs <app> [-t], Show the nginx access logs for an application (-t follows)
    nginx:error-logs <app> [-t], Show the nginx error logs for an application (-t follows)
    nginx:disable <app>, Disable nginx for an application (forces container binding to external interface)
    nginx:enable <app>, Enable nginx for an application
EOF
  ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
  ;;

esac
