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

# returns 'global', 'app', 'false'
# if both are configured, app trumps global
is_ssl_enabled() {
  local APP=$1; verify_app_name "$APP"
  APP_SSL_PATH="$DOKKU_ROOT/$APP/tls"

  if [[ -e "$APP_SSL_PATH/server.crt" ]] && [[ -e "$APP_SSL_PATH/server.key" ]]; then
    return 0
  else
    return 1
  fi
}

get_ssl_hostnames() {
  local APP=$1; verify_app_name "$APP"
  local SSL_PATH="$DOKKU_ROOT/$APP/tls"

  local SSL_HOSTNAME=$(openssl x509 -in "$SSL_PATH/server.crt" -noout -subject | tr '/' '\n' | grep CN= | cut -c4-)
  local SSL_HOSTNAME_ALT=$(openssl x509 -in "$SSL_PATH/server.crt" -noout -text | grep --after-context=1 '509v3 Subject Alternative Name:' | tail -n 1 | sed -e "s/[[:space:]]*DNS://g"  | tr ',' '\n' || true)
  if [[ -n "$SSL_HOSTNAME_ALT" ]]; then
    local SSL_HOSTNAMES="${SSL_HOSTNAME}\n${SSL_HOSTNAME_ALT}"
  else
    local SSL_HOSTNAMES=$SSL_HOSTNAME
  fi
  echo -e "$SSL_HOSTNAMES"
  return 0
}
