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

help_formatted (){
  echo -e 'Usage: dokku certs:COMMAND'
  echo ''
  echo 'Manage Dokku apps SSL (TLS) certs.'
  echo ''
  echo 'Additional commands:'
  help_content_func | sort | column -c2 -t -s,
}

help_content_func () {
      declare desc="return certs plugin help content"
      cat<<help_content
    certs, Manage Dokku apps SSL (TLS) certs
    certs:add <app> CRT KEY, Add an ssl endpoint to an app. Can also import from a tarball on stdin
    certs:chain CRT [CRT ...], [NOT IMPLEMENTED] Print the ordered and complete chain for the given certificate
    certs:generate <app> DOMAIN, Generate a key and certificate signing request (and self-signed certificate)
    certs:info <app>, Show certificate information for an ssl endpoint
    certs:key <app> CRT KEY [KEY ...], [NOT IMPLEMENTED] Print the correct key for the given certificate
    certs:remove <app>, Remove an SSL Endpoint from an app
    certs:rollback <app>, [NOT IMPLEMENTED] Rollback an SSL Endpoint for an app
    certs:update <app> CRT KEY, Update an SSL Endpoint on an app. Can also import from a tarball on stdin
help_content
    }

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
}
