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

is_tar_import() {
  declare desc="determines if we have STDIN open in an attempt to detect a streamed tar import"
  [[ -t 0 ]] && return 1
  return 0
}

is_file_import() {
  declare desc="determines if we have passed in a file and key path for a file import"
  local CRT_FILE="$1"
  local KEY_FILE="$2"

  if [[ $CRT_FILE ]] && [[ $KEY_FILE ]]; then
    if [[ ! -r $CRT_FILE ]]; then
      dokku_log_fail "CRT file specified not found, please check file paths"
    elif [[ ! -r $KEY_FILE ]]; then
      dokku_log_fail "KEY file specified not found, please check file paths"
    else
      return 0
    fi
  fi

  return 1
}

cmd-certs-set() {
  declare desc="imports an SSL cert/key combo either on STDIN via a tarball or from specified cert/key filenames"
  declare cmd="$1"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" CRT_FILE="$2" KEY_FILE="$3"

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

  if is_file_import "$CRT_FILE" "$KEY_FILE"; then
    # importing from file
    true
  elif is_tar_import; then
    local CERTS_SET_TMP_WORK_DIR=$(mktemp -d "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
    pushd "$CERTS_SET_TMP_WORK_DIR" &>/dev/null
    trap "popd &>/dev/null || true; rm -rf '$CERTS_SET_TMP_WORK_DIR' >/dev/null" RETURN
    tar xvf - <&0

    local CRT_FILE_SEARCH=$(find . -not -path '*/\.*' -type f | grep ".crt$")
    local CRT_FILE_COUNT=$(printf "%s" "$CRT_FILE_SEARCH" | grep -c '^')
    if [[ $CRT_FILE_COUNT -lt 1 ]]; then
      dokku_log_fail "Tar archive is missing .crt file"
    elif [[ $CRT_FILE_COUNT -gt 1 ]]; then
      dokku_log_fail "Tar archive contains more than one .crt file"
    else
      local CRT_FILE=$CRT_FILE_SEARCH
    fi

    local KEY_FILE_SEARCH=$(find . -not -path '*/\.*' -type f | grep ".key$")
    local KEY_FILE_COUNT=$(printf "%s" "$KEY_FILE_SEARCH" | grep -c '^')
    if [[ $KEY_FILE_COUNT -lt 1 ]]; then
      dokku_log_fail "Tar archive is missing .key file"
    elif [[ $KEY_FILE_COUNT -gt 1 ]]; then
      dokku_log_fail "Tar archive contains more than one .key file"
    else
      local KEY_FILE=$KEY_FILE_SEARCH
    fi
  else
    dokku_log_fail "Tar archive containing server.crt and server.key expected on stdin"
  fi

  mkdir -p "$APP_SSL_PATH"
  rm -f "$APP_SSL_PATH/server.crt" "$APP_SSL_PATH/server.key"
  cp "$CRT_FILE" "$APP_SSL_PATH/server.crt"
  cp "$KEY_FILE" "$APP_SSL_PATH/server.key"
  chmod 750 "$APP_SSL_PATH"
  chmod 640 "$APP_SSL_PATH/server.crt" "$APP_SSL_PATH/server.key"
  plugn trigger post-certs-update "$APP"
  plugn trigger post-domains-update "$APP"
}

cmd-certs-set "$@"
