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

certs_generate_cmd() {
  declare desc="generates a self-signed SSL certificate/key combo"
  local cmd="certs:generate"
  [[ -z $2 ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_app_name "$2"
  local APP="$2"; local DOMAIN="$3"; 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_certs.XXXXXXXXX")
    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 -des3 -passout pass:x -out server.pass.key 2048
    openssl rsa -passin pass:x -in server.pass.key -out server.key
    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.key" "$CERTS_GENERATE_TMP_WORK_DIR/server.crt" "$APP_SSL_PATH"
    chmod 750 "$APP_SSL_PATH"
    chmod 640 "$APP_SSL_PATH/server.key" "$APP_SSL_PATH/server.crt"
    [[ -n "$DOMAIN" ]] && (domains_add "$APP" "$DOMAIN" || nginx_build_config "$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 server.csr
  else
    dokku_log_info1 "$APP has an SSL endpoint already defined"
  fi
}

certs_generate_cmd "$@"
