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

cmd-domains-report() {
  declare desc="displays a domains report for one or more apps"
  declare cmd="domains:report"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" INFO_FLAG="$2"

  if [[ "$APP" == "--global" ]]; then
    cmd-domains-report-single "$APP" "$INFO_FLAG"
    return
  fi

  if [[ -n "$APP" ]] && [[ "$APP" == --* ]]; then
    INFO_FLAG="$APP"
    APP=""
  fi

  if [[ -z "$APP" ]] && [[ -z "$INFO_FLAG" ]]; then
    INFO_FLAG="true"
  fi

  if [[ -z "$APP" ]]; then
    for app in $(dokku_apps); do
      cmd-domains-report-single "$app" "$INFO_FLAG" | tee || true
    done
  else
    cmd-domains-report-single "$APP" "$INFO_FLAG"
  fi
}

cmd-domains-report-single() {
  declare APP="$1" INFO_FLAG="$2"
  if [[ "$INFO_FLAG" == "true" ]]; then
    INFO_FLAG=""
  fi
  local flag_map=() app_flags=() global_flags=()

  if [[ "$APP" != "--global" ]]; then
    verify_app_name "$APP"
    app_flags=(
      "--domains-app-enabled: $(fn-domains-app-enabled "$APP")"
      "--domains-app-vhosts: $(fn-domains-app-vhosts "$APP" | awk '{$1=$1};1')"
    )
  fi

  global_flags=(
    "--domains-global-enabled: $(fn-domains-global-enabled)"
    "--domains-global-vhosts: $(fn-domains-global-vhosts | awk '{$1=$1};1')"
  )

  flag_map=("${app_flags[@]}" "${global_flags[@]}")

  if [[ -z "$INFO_FLAG" ]]; then
    if [[ "$APP" == "--global" ]]; then
      dokku_log_info2_quiet "Global domains information"
    else
      dokku_log_info2_quiet "$APP domains information"
    fi
    for flag in "${flag_map[@]}"; do
      key="$(echo "${flag#--}" | cut -f1 -d' ' | tr - ' ')"
      dokku_log_verbose "$(printf "%-30s %-25s" "${key^}" "${flag#*: }")"
    done
  else
    local match=false
    local value_exists=false
    for flag in "${flag_map[@]}"; do
      valid_flags="${valid_flags} $(echo "$flag" | cut -d':' -f1)"
      if [[ "$flag" == "${INFO_FLAG}:"* ]]; then
        value=${flag#*: }
        size="${#value}"
        if [[ "$size" -ne 0 ]]; then
          echo "$value" && match=true && value_exists=true
        else
          match=true
        fi
      fi
    done
    [[ "$match" == "true" ]] || dokku_log_fail "Invalid flag passed, valid flags:${valid_flags}"
  fi
}

fn-domains-app-enabled() {
  declare APP="$1"
  local DOMAINS_APP_ENABLED=false
  if [[ "$(is_app_vhost_enabled "$APP")" == "true" ]]; then
    DOMAINS_APP_ENABLED=true
  fi
  echo "$DOMAINS_APP_ENABLED"
}

fn-domains-app-vhosts() {
  declare APP="$1"
  local APP_VHOST_PATH="$DOKKU_ROOT/$APP/VHOST"
  if [[ -f "$APP_VHOST_PATH" ]]; then
    tr '\n' ' ' <"$APP_VHOST_PATH"
  fi
}

fn-domains-global-enabled() {
  local DOMAINS_GLOBAL_ENABLED=false
  if [[ "$(is_global_vhost_enabled)" == "true" ]]; then
    DOMAINS_GLOBAL_ENABLED=true
  fi
  echo "$DOMAINS_GLOBAL_ENABLED"
}

fn-domains-global-vhosts() {
  if [[ "$(is_global_vhost_enabled)" == "true" ]]; then
    get_global_vhosts | tr '\n' ' '
  fi
}

fn-domains-generate-urls() {
  declare APP="$1" DEFAULT_SCHEME="$2" DEFAULT_LISTEN_PORT="$3"

  local app_vhosts="$(plugn trigger domains-list "$APP")"
  if [[ -n "$app_vhosts" ]]; then
    for app_vhost in $app_vhosts; do
      fn-domains-generate-urls-from-config "$APP" "$DEFAULT_SCHEME" "$app_vhost" "$DEFAULT_LISTEN_PORT"
    done
  else
    if [[ -s "$DOKKU_ROOT/VHOST" ]]; then
      while read -r VHOST || [[ -n "$VHOST" ]]; do
        fn-domains-generate-urls-from-config "$APP" "$DEFAULT_SCHEME" "$VHOST" "$DEFAULT_LISTEN_PORT"
      done <"$DOKKU_ROOT/VHOST"
    else
      fn-domains-generate-urls-from-config "$APP" "$DEFAULT_SCHEME" "$(hostname -f)" "$DEFAULT_LISTEN_PORT"
    fi
  fi
}

fn-domains-generate-urls-from-config() {
  declare APP="$1" DEFAULT_SCHEME="$2" VHOST="$3" DEFAULT_LISTEN_PORT="$4"
  local APP_PORT_MAP="$(plugn trigger ports-get "$APP")"

  if [[ "$(plugn trigger proxy-is-enabled "$APP")" == "false" ]]; then
    local DOKKU_APP_WEB_LISTENERS PORT
    DOKKU_APP_WEB_LISTENERS="$(plugn trigger network-get-listeners "$APP" "web" | xargs)"
    for DOKKU_APP_WEB_LISTENER in $DOKKU_APP_WEB_LISTENERS; do
      listen_port="$(echo "$DOKKU_APP_WEB_LISTENER" | cut -d ':' -f2)"
      fn-domains-generate-url "$DEFAULT_SCHEME" "$VHOST" "$listen_port"
    done
    shopt -u nullglob
  elif [[ -n "$APP_PORT_MAP" ]]; then
    CERTS_EXIST="$(plugn trigger certs-exists "$APP")"
    local port_map
    while IFS= read -r port_map; do
      local scheme="$(awk -F ':' '{ print $1 }' <<<"$port_map")"
      local listen_port="$(awk -F ':' '{ print $2 }' <<<"$port_map")"
      if [[ "$CERTS_EXIST" != "true" ]] && [[ "$scheme" == "https" ]]; then
        continue
      fi
      fn-domains-generate-url "$scheme" "$VHOST" "$listen_port"
    done <<<"$APP_PORT_MAP"
  else
    fn-domains-generate-url "$DEFAULT_SCHEME" "$VHOST" "$DEFAULT_LISTEN_PORT"
  fi
}

fn-domains-generate-url() {
  declare SCHEME="$1" VHOST="$2" PORT="$3"
  if [[ "$PORT" == "80" ]]; then
    echo "http://$VHOST"
  elif [[ "$PORT" == "443" ]]; then
    if [[ "$SCHEME" == "https" ]]; then
      echo "https://$VHOST"
    else
      echo "$SCHEME://$VHOST:$PORT"
    fi
  else
    echo "$SCHEME://$VHOST:$PORT"
  fi
}
