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

certs_info_cmd() {
  # This is here because it's used in both the info and the default
  declare desc="prints SSL certificate info for app"
  local cmd="certs:info"
  [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_app_name "$2"
  local APP="$2"; local APP_SSL_PATH="$DOKKU_ROOT/$APP/tls"

  if [[ -n "$APP_SSL_PATH" ]]; then
    dokku_log_info1 "Fetching SSL Endpoint info for $APP..."
    dokku_log_info1 "Certificate details:"
    dokku_log_info2 "Common Name(s): "

    for domain in $(get_ssl_hostnames "$APP" | xargs); do
      dokku_log_info2 "   $domain"
    done

    dokku_log_info2 "Expires At: $(openssl x509 -in "$APP_SSL_PATH/server.crt" -noout -text | grep "Not After :" | awk -F " : " '{ print $2 }')"
    dokku_log_info2 "Issuer: $(openssl x509 -in "$APP_SSL_PATH/server.crt" -noout -text | grep "Issuer:" | xargs | sed -e "s/Issuer: //g")"
    dokku_log_info2 "Starts At: $(openssl x509 -in "$APP_SSL_PATH/server.crt" -noout -text | grep "Not Before:" | awk -F ": " '{ print $2 }')"
    dokku_log_info2 "Subject: $(openssl x509 -in "$APP_SSL_PATH/server.crt" -noout -subject | sed -e "s:subject= ::g"| sed -e "s:^/::g" | sed -e "s:/:; :g")"
    local SSL_VERIFY_OUTPUT="$(openssl verify -verbose -purpose sslserver "$APP_SSL_PATH/server.crt" | awk -F ':' '{ print $2 }' | tail -1 | xargs || true)"
    if [[ "$SSL_VERIFY_OUTPUT" == "OK" ]]; then
      local SSL_SELF_SIGNED="verified by a certificate authority."
    else
      local SSL_SELF_SIGNED="self signed."
    fi
    dokku_log_info2 "SSL certificate is $SSL_SELF_SIGNED"
  else
    dokku_log_info1 "$APP does not have an SSL endpoint"
  fi
}

is_ssl_enabled() {
  declare desc="returns 0 if ssl is enabled for given app"
  local APP=$1; verify_app_name "$APP"
  local 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() {
  declare desc="returns a string of ssl hostnames extracted from an app's ssl certificate"
  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" | sort -u
  return 0
}
