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

cmd-certs-generate() {
  declare desc="generates a self-signed SSL certificate/key combo"
  declare cmd="certs:generate"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" DOMAIN="$2"

  verify_app_name "$APP"
  local APP_SSL_PATH="$DOKKU_ROOT/$APP/tls"

  if [[ ! -f "$APP_SSL_PATH/server.key" ]] && [[ ! -f "$APP_SSL_PATH/server.crt" ]]; then
    local CERTS_GENERATE_TMP_WORK_DIR=$(mktemp -d "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
    pushd "$CERTS_GENERATE_TMP_WORK_DIR" >/dev/null
    trap "popd &>/dev/null || true; rm -rf '$CERTS_GENERATE_TMP_WORK_DIR' >/dev/null" INT TERM EXIT

    openssl genrsa -out server.key 2048
    openssl req -new -key server.key -out server.csr
    openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

    mkdir -p "$APP_SSL_PATH"
    dokku_log_info1 "Installing certificate and key..."
    mv -f "$CERTS_GENERATE_TMP_WORK_DIR/server.crt" "$CERTS_GENERATE_TMP_WORK_DIR/server.csr" "$CERTS_GENERATE_TMP_WORK_DIR/server.key" "$APP_SSL_PATH"
    chmod 750 "$APP_SSL_PATH"
    chmod 640 "$APP_SSL_PATH/server.crt" "$APP_SSL_PATH/server.csr" "$APP_SSL_PATH/server.key"
    plugn trigger post-certs-update "$APP"
    [[ -n "$DOMAIN" ]] && (plugn trigger domains-add "$APP" "$DOMAIN" || plugn trigger post-domains-update "$APP")
    dokku_log_info1 "The following is a certificate signing request that can be used"
    dokku_log_info1 "to generate an 'officially' signed SSL certificate for $APP at $DOMAIN"
    dokku_log_info1 "by a CA of your choosing."
    cat "$APP_SSL_PATH/server.csr"
  else
    dokku_log_info1 "$APP has an SSL endpoint already defined"
  fi
}

cmd-certs-generate "$@"
