#!/usr/bin/env bash
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/certs/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/domains/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/nginx-vhosts/functions"
if [[ -f "$PLUGIN_CORE_AVAILABLE_PATH/nginx-vhosts/internal-functions" ]]; then
  source "$PLUGIN_CORE_AVAILABLE_PATH/nginx-vhosts/internal-functions"
fi
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/config"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

fn-letsencrypt-detect-rate-limit() {
  declare desc="return 0 when the captured lego log shows an ACME rate-limit response"
  declare LOG_PATH="$1"

  [[ -f "$LOG_PATH" ]] || return 1
  grep -qE 'urn:ietf:params:acme:error:rateLimited|\b429\b.*[Tt]oo [Mm]any [Rr]equests|too many certificates|too many failed authorizations' "$LOG_PATH"
}

fn-letsencrypt-log-rate-limit() {
  declare desc="emit a friendly warning when the ACME server has rate-limited the request"
  declare APP="$1"

  dokku_log_warn "Let's Encrypt rate-limited this request."
  dokku_log_warn "See https://letsencrypt.org/docs/rate-limits/ for the active limits and remediation guidance."
  dokku_log_warn "Use 'dokku letsencrypt:set ${APP:-<app>} server staging' while iterating to avoid the production limits."
}

fn-letsencrypt-shared-accounts-dir() {
  declare desc="dokku-host path to the shared lego accounts directory"
  echo "$DOKKU_LIB_ROOT/data/letsencrypt/--global/accounts"
}

fn-letsencrypt-shared-accounts-host-dir() {
  declare desc="docker-host path to the shared lego accounts directory"
  echo "$DOKKU_LIB_HOST_ROOT/data/letsencrypt/--global/accounts"
}

fn-letsencrypt-ensure-shared-accounts-dir() {
  declare desc="create the shared lego accounts directory with strict permissions"
  local accounts_dir
  accounts_dir="$(fn-letsencrypt-shared-accounts-dir)"
  mkdir -p "$accounts_dir"
  # account keys live here; restrict to the dokku user.
  chmod 0700 "$accounts_dir"
}

fn-letsencrypt-ensure-app-webroot-dir() {
  declare desc="create the per-app ACME webroot with world-traversable perms"
  declare APP="$1"
  local webroot
  webroot="$DOKKU_LIB_ROOT/data/letsencrypt/$APP"
  mkdir -p "$webroot"
  # nginx must traverse this directory to serve /.well-known/acme-challenge
  # files. The files are public by design (ACME HTTP-01 fetches them over
  # plain HTTP), and not every dokku install puts www-data in the dokku
  # group, so pin 0755 instead of relying on the invoker's umask.
  chmod 0755 "$webroot"
}

fn-letsencrypt-account-server-dir() {
  declare desc="lego-style directory name derived from the configured ACME server URL"
  declare APP="$1"
  local server host

  server="$(fn-letsencrypt-computed-server "$APP")"
  host="${server#http://}"
  host="${host#https://}"
  host="${host%%/*}"
  # lego stores accounts under a host segment with ':' replaced by '_'
  host="${host//:/_}"
  echo "$host"
}

fn-letsencrypt-shared-account-exists() {
  declare desc="return 0 when the shared accounts dir holds an account for this app's (server, email)"
  declare APP="$1"
  local server_dir email accounts_dir

  server_dir="$(fn-letsencrypt-account-server-dir "$APP")"
  email="$(fn-letsencrypt-computed-email "$APP")"
  if [[ -z "$server_dir" ]] || [[ -z "$email" ]]; then
    return 1
  fi
  accounts_dir="$(fn-letsencrypt-shared-accounts-dir)"
  [[ -f "$accounts_dir/$server_dir/$email/account.json" ]]
}

fn-letsencrypt-acme-execute-challenge() {
  declare desc="perform actual ACME validation procedure"
  declare APP="$1"
  local FAKE_NGINX_CONF=false
  local challenge_mode config_dir

  if [[ ! -f "$DOKKU_ROOT/$APP/nginx.conf" ]]; then
    FAKE_NGINX_CONF=true
  fi

  fn-letsencrypt-create-root "$APP"

  challenge_mode="HTTP-01"
  dns_provider="$(fn-letsencrypt-computed-dns-provider "$APP")"
  if [[ -n "$dns_provider" ]]; then
    challenge_mode="DNS-01"
  fi

  dokku_log_info1 "Getting letsencrypt certificate for ${APP} via ${challenge_mode}"

  # read arguments from appropriate config file into the config array
  config_dirs="$(fn-letsencrypt-configure-and-get-dir "$APP")"
  host_config_dir="$(echo "$config_dirs" | cut -d: -f1)"
  container_config_dir="$(echo "$config_dirs" | cut -d: -f2)"
  read -r -a config <"$container_config_dir/config"
  local docker_options_argv=()
  if [[ -f "$container_config_dir/docker_options" ]]; then
    read -r -a docker_options_argv <"$container_config_dir/docker_options"
  fi

  # run letsencrypt as a docker container using "certonly" mode
  # port 80 of the standalone webserver will be forwarded by the proxy
  local lego_log shared_accounts_lock
  lego_log="$(mktemp)"
  set +e
  export DOKKU_UID=$(id -u)
  export DOKKU_GID=$(id -g)
  fn-letsencrypt-ensure-app-webroot-dir "$APP"
  fn-letsencrypt-ensure-shared-accounts-dir
  shared_accounts_lock="$(fn-letsencrypt-shared-accounts-dir)/.lock"
  {
    flock -x 9
    docker run --rm \
      --env-file "$container_config_dir/docker.env" \
      --user $DOKKU_UID:$DOKKU_GID \
      -v "$host_config_dir:/certs" \
      -v "$DOKKU_LIB_HOST_ROOT/data/letsencrypt/$APP:/webroot" \
      -v "$(fn-letsencrypt-shared-accounts-host-dir):/certs/accounts" \
      "${docker_options_argv[@]}" \
      "${PLUGIN_IMAGE}:${PLUGIN_IMAGE_VERSION}" \
      "${config[@]}" run 2>&1
  } 9>"$shared_accounts_lock" | tee "$lego_log" | sed "s/^/       /"

  local exit_code=${PIPESTATUS[0]}
  set -e

  if [[ "$FAKE_NGINX_CONF" == "true" ]]; then
    rm "$DOKKU_ROOT/$APP/nginx.conf"
  fi

  if [[ $exit_code != 0 ]]; then
    if fn-letsencrypt-detect-rate-limit "$lego_log"; then
      fn-letsencrypt-log-rate-limit "$APP"
    fi
    rm -f "$lego_log"
    dokku_log_info1 "Certificate retrieval failed!"
    return $exit_code
  fi

  rm -f "$lego_log"

  # got certificate
  dokku_log_info1 "Certificate retrieved successfully."
  fn-letsencrypt-symlink-certs "$APP" "$container_config_dir"
  plugn trigger proxy-build-config "$APP"
}

fn-letsencrypt-acme-revoke() {
  declare desc="perform actual certificate revocation"
  local APP="$1"

  fn-letsencrypt-create-root "$APP"

  challenge_mode="HTTP-01"
  dns_provider="$(fn-letsencrypt-computed-dns-provider "$APP")"
  if [[ -n "$dns_provider" ]]; then
    challenge_mode="DNS-01"
  fi

  dokku_log_info1 "Revoking letsencrypt certificate for ${APP} via ${challenge_mode}"
  local acme_port="$(plugn trigger ports-get-available)"
  if [[ -z "$acme_port" ]]; then
    acme_port="$(get_available_port)"
  fi

  # read arguments from appropriate config file into the config array
  config_dirs="$(fn-letsencrypt-configure-and-get-dir "$APP")"
  host_config_dir="$(echo "$config_dirs" | cut -d: -f1)"
  container_config_dir="$(echo "$config_dirs" | cut -d: -f2)"
  read -r -a config <"$container_config_dir/config"
  local docker_options_argv=()
  if [[ -f "$container_config_dir/docker_options" ]]; then
    read -r -a docker_options_argv <"$container_config_dir/docker_options"
  fi

  # run letsencrypt as a docker container using "certonly" mode
  # port 80 of the standalone webserver will be forwarded by the proxy
  local lego_log shared_accounts_lock
  lego_log="$(mktemp)"
  set +e
  export DOKKU_UID=$(id -u)
  export DOKKU_GID=$(id -g)
  fn-letsencrypt-ensure-app-webroot-dir "$APP"
  fn-letsencrypt-ensure-shared-accounts-dir
  shared_accounts_lock="$(fn-letsencrypt-shared-accounts-dir)/.lock"

  # Only overlay the shared accounts dir when it holds the matching
  # (server, email) account; otherwise fall back to the per-app account
  # so revocation of certs issued before the shared-account change still works.
  local account_volume_args=()
  if fn-letsencrypt-shared-account-exists "$APP"; then
    account_volume_args=(-v "$(fn-letsencrypt-shared-accounts-host-dir):/certs/accounts")
  fi

  {
    flock -x 9
    docker run --rm \
      --env-file "$container_config_dir/docker.env" \
      --user $DOKKU_UID:$DOKKU_GID \
      -p "$acme_port:$acme_port" \
      -v "$host_config_dir:/certs" \
      -v "$DOKKU_LIB_HOST_ROOT/data/letsencrypt/$APP:/webroot" \
      "${account_volume_args[@]}" \
      "${docker_options_argv[@]}" \
      "${PLUGIN_IMAGE}:${PLUGIN_IMAGE_VERSION}" \
      "${config[@]}" revoke 2>&1
  } 9>"$shared_accounts_lock" | tee "$lego_log" | sed "s/^/       /"

  local exit_code=${PIPESTATUS[0]}
  set -e

  # handle return codes
  if [[ $exit_code == 0 ]]; then
    # certificate revoked
    dokku_log_info1 "Certificate revoked successfully."
  else
    # error - don't try to link certificates
    if fn-letsencrypt-detect-rate-limit "$lego_log"; then
      fn-letsencrypt-log-rate-limit "$APP"
    fi
    rm -f "$lego_log"
    dokku_log_info1 "Certificate revocation failed (code $exit_code)!"
    return
  fi

  rm -f "$lego_log"

  local domain="$(fn-letsencrypt-app-domains "$APP" | xargs | awk '{print $1}')"

  # removing the certificate will automatically reconfigure nginx
  if [[ -z $DOKKU_APP_NAME ]]; then
    dokku certs:remove "$APP"
  else
    dokku certs:remove
  fi
}

fn-letsencrypt-acme-proxy-disable() {
  declare desc="disable ACME proxy for an app"
  local APP="$1"

  local app_root="$DOKKU_ROOT/$APP"
  local app_config_dir="$app_root/nginx.conf.d"

  dokku_log_info1 "Disabling ACME proxy for $APP..."

  [[ -f "$app_config_dir/letsencrypt.conf" ]] && rm "$app_config_dir/letsencrypt.conf"

  restart_nginx | sed "s/^/       /"
}

fn-letsencrypt-acme-proxy-enable() {
  declare desc="enable ACME proxy for an app"
  local APP="$1"

  local app_root="$DOKKU_ROOT/$APP"
  local app_config_dir="$app_root/nginx.conf.d"

  dokku_log_info1 "Enabling ACME proxy for ${APP}..."

  # ensure the nginx.conf.d directory exists
  [[ -d "$app_config_dir" ]] || mkdir "$app_config_dir"

  # generate letsencrypt config
  sigil -f "$PLUGIN_AVAILABLE_PATH/letsencrypt/templates/letsencrypt.conf.sigil" \
    APP="$APP" \
    DOKKU_LIB_ROOT="$DOKKU_LIB_ROOT" \
    >"$app_config_dir/letsencrypt.conf"

  restart_nginx | sed "s/^/       /"
}

fn-letsencrypt-ensure-http-port() {
  declare desc="ensure the app has an http:80 proxy mapping so nginx can serve the HTTP-01 challenge"
  declare APP="$1"
  local port_map line container_port

  # HTTP-01 is the only challenge type that needs a listener on port 80; the
  # DNS-01 flow never hits nginx.
  if [[ -n "$(fn-letsencrypt-computed-dns-provider "$APP")" ]]; then
    return 0
  fi

  port_map="$(plugn trigger ports-get "$APP" 2>/dev/null || true)"

  while IFS= read -r line; do
    [[ "$line" == http:80:* ]] && return 0
  done <<<"$port_map"

  container_port=""
  while IFS= read -r line; do
    if [[ "$line" == http:*:* ]]; then
      container_port="${line##*:}"
      break
    fi
  done <<<"$port_map"

  if [[ -z "$container_port" ]]; then
    while IFS= read -r line; do
      if [[ "$line" == https:*:* ]]; then
        container_port="${line##*:}"
        break
      fi
    done <<<"$port_map"
  fi

  if [[ -z "$container_port" ]]; then
    dokku_log_warn "Cannot enable letsencrypt for $APP: no http or https proxy port mapping was found."
    dokku_log_warn "  letsencrypt needs an http listener on port 80 to serve the ACME HTTP-01 challenge."
    dokku_log_warn "  Add one with: dokku ports:add $APP http:80:<container-port>"
    return 1
  fi

  dokku_log_info1 "Adding http:80:${container_port} port mapping to ${APP} for ACME HTTP-01 challenge..."
  dokku ports:add "$APP" "http:80:${container_port}" | sed "s/^/       /"
}

fn-letsencrypt-computed-dns-provider() {
  declare desc="get configured dns provider, with 'none' as an explicit opt-out sentinel"
  declare APP="$1"
  local value

  value="$(fn-letsencrypt-dns-provider "$APP")"
  if [[ "$value" == "none" ]]; then
    echo ""
    return
  fi
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-dns-provider)"
  fi
  if [[ "$value" == "none" ]]; then
    value=""
  fi

  echo "$value"
}

fn-letsencrypt-global-dns-provider() {
  declare desc="get configured dns provider"

  fn-plugin-property-get-default "letsencrypt" "--global" "dns-provider" ""
}

fn-letsencrypt-dns-provider() {
  declare desc="get configured dns provider"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "dns-provider" ""
}

fn-letsencrypt-computed-lego-args() {
  declare desc="get configured lego cli args"
  declare APP="$1"

  value="$(fn-letsencrypt-lego-args "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-lego-args)"
  fi

  echo "$value"
}

fn-letsencrypt-global-lego-args() {
  declare desc="get configured lego cli args"

  fn-plugin-property-get-default "letsencrypt" "--global" "lego-args" ""
}

fn-letsencrypt-lego-args() {
  declare desc="get configured lego cli args"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "lego-args" ""
}

fn-letsencrypt-computed-lego-docker-options() {
  declare desc="get configured docker run options for the lego container"
  declare APP="$1"

  value="$(fn-letsencrypt-lego-docker-options "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-lego-docker-options)"
  fi

  echo "$value"
}

fn-letsencrypt-global-lego-docker-options() {
  declare desc="get configured docker run options for the lego container"

  fn-plugin-property-get-default "letsencrypt" "--global" "lego-docker-options" ""
}

fn-letsencrypt-lego-docker-options() {
  declare desc="get configured docker run options for the lego container"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "lego-docker-options" ""
}

fn-letsencrypt-app-domains() {
  declare desc="list app domains, skipping the '_' nginx default-vhost sentinel"
  declare APP="$1"
  get_app_domains "$APP" | grep -vxF '_' || true
}

fn-letsencrypt-check-email() {
  declare desc="Check if an e-mail address is provided globally or for the app"
  declare APP="$1"

  # check we have a valid e-mail address
  if [[ -z "$(fn-letsencrypt-computed-email "$APP")" ]]; then
    dokku_log_warn "ERROR: Cannot request a certificate without an e-mail address!"
    dokku_log_warn "  please provide your e-mail address using"
    dokku_log_warn "  dokku letsencrypt:set $APP email <e-mail>"
    return 1
  fi
}

fn-letsencrypt-config-string() {
  declare desc="assemble the lego command-line config string (no side effects)"
  declare APP="$1"
  local cert_timeout config dns_provider domain domain_args domains email extra_args server

  server="$(fn-letsencrypt-computed-server "$APP")"

  domains="$(fn-letsencrypt-app-domains "$APP")"
  domain_args=''
  for domain in $domains; do
    domain_args="$domain_args --domains $domain"
  done

  cert_timeout=30
  email="$(fn-letsencrypt-computed-email "$APP")"
  extra_args="$(fn-letsencrypt-computed-lego-args "$APP")"
  config="--pem --accept-tos --cert.timeout $cert_timeout --path /certs --server $server --email $email $extra_args $domain_args"

  dns_provider="$(fn-letsencrypt-computed-dns-provider "$APP")"
  if [[ -n "$dns_provider" ]]; then
    config="--dns $dns_provider $config"
  else
    config="--http --http.webroot /webroot $config"
  fi

  echo "$config"
}

fn-letsencrypt-config-hash() {
  declare desc="compute the sha1 hash that names an app's lego config directory"
  declare APP="$1"
  local config docker_options_value

  config="$(fn-letsencrypt-config-string "$APP")"
  docker_options_value="$(fn-letsencrypt-computed-lego-docker-options "$APP")"
  echo "$config $docker_options_value" | sha1sum | awk '{print $1}'
}

fn-letsencrypt-configure-and-get-dir() {
  declare desc="assemble lego command line arguments and create a config hash directory for them"
  declare APP="$1"
  local config config_dir config_hash dns_provider docker_options_value domain key value

  local app_root="$DOKKU_ROOT/$APP"
  local le_root="$app_root/letsencrypt"

  for domain in $(fn-letsencrypt-app-domains "$APP"); do
    dokku_log_verbose " - Domain '$domain'" >&2
  done

  config="$(fn-letsencrypt-config-string "$APP")"
  docker_options_value="$(fn-letsencrypt-computed-lego-docker-options "$APP")"
  dns_provider="$(fn-letsencrypt-computed-dns-provider "$APP")"

  config_hash="$(fn-letsencrypt-config-hash "$APP")"
  config_dir="$le_root/certs/$config_hash"
  mkdir -p "$config_dir"

  rm -f "$config_dir/docker.env"
  touch "$config_dir/docker.env"
  if [[ -n "$dns_provider" ]]; then
    fn-plugin-property-get-all "letsencrypt" "--global" | while read -r line; do
      [[ -n "$line" ]] || continue
      key="$(cut -d" " -f1 <<<"$line")"
      if [[ "$key" == dns-provider-* ]]; then
        value="$(cut -d" " -f2- <<<"$line")"
        echo "${key#"dns-provider-"}=$value" >>"$config_dir/docker.env"
      fi
    done
    fn-plugin-property-get-all "letsencrypt" "$APP" | while read -r line; do
      [[ -n "$line" ]] || continue
      key="$(cut -d" " -f1 <<<"$line")"
      if [[ "$key" == dns-provider-* ]]; then
        value="$(cut -d" " -f2- <<<"$line")"
        echo "${key#"dns-provider-"}=$value" >>"$config_dir/docker.env"
      fi
    done
  fi

  # ensure the permissions are set correctly on anything that may expose api keys
  chmod 0755 "$config_dir/docker.env"

  # store config settings
  echo "$config" >"$config_dir/config"
  echo "$docker_options_value" >"$config_dir/docker_options"

  # send both host and container path
  # to respect mapped DOKKU_ROOT when running in a container
  echo "$DOKKU_HOST_ROOT/$APP/letsencrypt/certs/$config_hash:$config_dir"
}

fn-letsencrypt-cron-job-enabled() {
  declare desc="Check if the cron plugin is available"

  if [[ ! -f "$PLUGIN_AVAILABLE_PATH/cron/cron-write" ]]; then
    return 1
  fi
}

fn-letsencrypt-cron-job-add() {
  declare desc="Add auto-renew cronjob to dokku user's crontab"

  mkdir -p "${DOKKU_LIB_ROOT}/data/letsencrypt/--global"
  touch "${DOKKU_LIB_ROOT}/data/letsencrypt/--global/autorenew"
  if fn-letsencrypt-cron-job-enabled; then
    plugn trigger cron-write
  else
    crons="$(crontab -l || true)"
    crons="$(grep -v -F "$LETSENCRYPT_CRON_CMD" <<<"$crons")"
    printf "%s\n%s\n" "$crons" "$LETSENCRYPT_CRON_JOB" | crontab -
  fi

  dokku_log_info1 "Added cron job to dokku's crontab."
}

fn-letsencrypt-cron-job-remove() {
  declare desc="Remove auto-renew cronjob from dokku user's crontab"

  rm -f "${DOKKU_LIB_ROOT}/data/letsencrypt/--global/autorenew"
  if fn-letsencrypt-cron-job-enabled; then
    plugn trigger cron-write
  else
    crons="$(crontab -l || true)"
    crons="$(grep -v -F "$LETSENCRYPT_CRON_CMD" <<<"$crons")"
    printf "%s" "$crons" | crontab -
  fi
  dokku_log_info1 "Removed cron job from dokku's crontab."
}

fn-letsencrypt-create-root() {
  declare desc="Ensure the let's encrypt root directory exists"
  declare APP="$1"
  local NGINX_ACCESS_LOG_FORMAT NGINX_ACCESS_LOG_PATH NGINX_ERROR_LOG_PATH

  local app_root="$DOKKU_ROOT/$APP"
  local le_root="$app_root/letsencrypt"

  mkdir -p "$le_root"

  if [[ ! -f "$DOKKU_ROOT/$APP/nginx.conf" ]]; then
    dokku_log_info1 "Setting temporary site"
    NGINX_ACCESS_LOG_FORMAT="$(fn-nginx-access-log-format "$APP")"
    NGINX_ACCESS_LOG_PATH="$(fn-nginx-access-log-path "$APP")"
    NGINX_ERROR_LOG_PATH="$(fn-nginx-error-log-path "$APP")"
    if [[ -z "$NGINX_ACCESS_LOG_FORMAT" ]]; then
      NGINX_ACCESS_LOG_FORMAT="$(fn-nginx-computed-access-log-format "$APP")"
    fi
    if [[ -z "$NGINX_ACCESS_LOG_PATH" ]]; then
      NGINX_ACCESS_LOG_PATH="$(fn-nginx-computed-access-log-path "$APP")"
    fi
    if [[ -z "$NGINX_ERROR_LOG_PATH" ]]; then
      NGINX_ERROR_LOG_PATH="$(fn-nginx-computed-error-log-path "$APP")"
    fi

    sigil -f "$PLUGIN_AVAILABLE_PATH/letsencrypt/templates/default-nginx.conf.sigil" \
      DOMAINS="$(fn-letsencrypt-app-domains "$APP" | xargs)" DOKKU_ROOT="$DOKKU_ROOT" APP="$APP" \
      NGINX_ACCESS_LOG_FORMAT="$NGINX_ACCESS_LOG_FORMAT" NGINX_ACCESS_LOG_PATH="$NGINX_ACCESS_LOG_PATH" \
      NGINX_ERROR_LOG_PATH="$NGINX_ERROR_LOG_PATH" \
      >"$DOKKU_ROOT/$APP/nginx.conf"
    restart_nginx | sed "s/^/       /"
  fi
}

fn-letsencrypt-is-autorenew-enabled() {
  declare desc="check if autorenew is enabled"
  local enabled=false

  if [[ -f "${DOKKU_LIB_ROOT}/data/letsencrypt/--global/autorenew" ]]; then
    enabled=true
  fi

  echo "$enabled"
}

fn-letsencrypt-computed-email() {
  declare desc="get configured email address"
  declare APP="$1"

  value="$(fn-letsencrypt-email "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-email)"
  fi

  echo "$value"
}

fn-letsencrypt-global-email() {
  declare desc="get configured email address"

  fn-plugin-property-get-default "letsencrypt" "--global" "email" ""
}

fn-letsencrypt-email() {
  declare desc="get configured email address"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "email" ""
}

fn-letsencrypt-enable() {
  declare APP="$1" FORCE="${2:-false}"
  local EXIT_CODE=0
  local domain

  verify_app_name "$APP"

  domain="$(fn-letsencrypt-app-domains "$APP" | xargs | awk '{print $1}')"
  if [[ -z "$domain" ]]; then
    dokku_log_warn "No domains detected for $APP"
    return 1
  fi

  dokku_log_info2 "Enabling letsencrypt for $APP"

  fn-letsencrypt-check-email "$APP"

  if [[ "$FORCE" != "true" ]] && ! fn-letsencrypt-needs-issue "$APP"; then
    dokku_log_info1 "Certificate is still valid for $APP, skipping certificate request"
    dokku_log_info1 "Pass --force to letsencrypt:enable to request a new certificate anyway"
    return 0
  fi

  fn-letsencrypt-ensure-http-port "$APP"
  fn-letsencrypt-acme-proxy-enable "$APP"
  fn-letsencrypt-acme-execute-challenge "$APP" || EXIT_CODE=$? # remove ACME proxy even if this fails
  fn-letsencrypt-acme-proxy-disable "$APP"

  if [[ "$EXIT_CODE" == 0 ]]; then
    dokku_log_info1 "Done"
    return
  fi

  dokku_log_warn "Failed to setup letsencrypt"
  DOKKU_FAIL_EXIT_CODE="$EXIT_CODE" dokku_log_fail "Check log output for further information on failure"
}

fn-letsencrypt-needs-issue() {
  declare desc="return 0 when the app needs a fresh certificate, 1 when the current one is still valid"
  declare APP="$1"
  local current_link configured_hash current_hash expiry grace_period time_to_renewal

  if [[ "$(fn-letsencrypt-is-active "$APP")" != "true" ]]; then
    return 0
  fi

  current_link="$DOKKU_ROOT/$APP/letsencrypt/certs/current"
  if [[ ! -L "$current_link" ]]; then
    return 0
  fi

  configured_hash="$(fn-letsencrypt-config-hash "$APP")"
  current_hash="$(basename "$(readlink "$current_link")")"
  if [[ "$current_hash" != "$configured_hash" ]]; then
    return 0
  fi

  expiry="$(fn-letsencrypt-expiration "$APP")"
  if [[ -z "$expiry" ]]; then
    return 0
  fi

  grace_period="$(fn-letsencrypt-computed-graceperiod "$APP")"
  time_to_renewal=$((expiry - grace_period - $(date +%s)))
  if [[ $time_to_renewal -lt 0 ]]; then
    return 0
  fi

  return 1
}

fn-letsencrypt-expiration() {
  declare desc="prints expiration time"
  declare APP="$1"

  if [[ -f "$DOKKU_ROOT/$APP/tls/server.letsencrypt.crt" ]]; then
    date -u -d "$(openssl x509 -in "$DOKKU_ROOT/$APP/tls/server.letsencrypt.crt" -enddate -noout | sed -e "s/^notAfter=//")" "+%s"
  elif [[ -f "$DOKKU_ROOT/$APP/tls/server.crt" ]]; then
    date -u -d "$(openssl x509 -in "$DOKKU_ROOT/$APP/tls/server.crt" -enddate -noout | sed -e "s/^notAfter=//")" "+%s"
  fi
}

fn-letsencrypt-computed-graceperiod() {
  declare desc="get configured graceperiod"
  declare APP="$1"
  local value

  value="$(fn-letsencrypt-graceperiod "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-graceperiod)"
  fi

  if [[ -z "$value" ]]; then
    value="$((60 * 60 * 24 * 30))"
  fi

  echo "$value"
}

fn-letsencrypt-global-graceperiod() {
  declare desc="get configured graceperiod"

  fn-plugin-property-get-default "letsencrypt" "--global" "graceperiod" ""
}

fn-letsencrypt-graceperiod() {
  declare desc="get configured graceperiod"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "graceperiod" ""
}

fn-letsencrypt-format-timediff() {
  declare desc="format a time difference in seconds into a human-readable string"
  local td="$1"
  local negative_td=0

  if [ "$td" -lt 0 ]; then
    negative_td=1
    td=$((-td))
  fi

  local days=$((td / (24 * 60 * 60)))
  td=$((td % (24 * 60 * 60)))

  local hours=$((td / (60 * 60)))
  td=$((td % (60 * 60)))

  local minutes=$((td / 60))
  local secs=$((td % 60))

  local res=""
  if [ $days -gt 0 ]; then
    res="${days}d, "
  fi

  if [ $hours -gt 0 ]; then
    res="${res}${hours}h, "
  fi

  if [ $minutes -gt 0 ]; then
    res="${res}${minutes}m, "
  fi

  if [ $secs -gt 0 ]; then
    res="${res}${secs}s, "
  fi

  # remove trailing comma
  res="$(echo "$res" | sed -re 's/, ?$//g')"

  if [[ $negative_td == 1 ]]; then
    res="${res} ago"
  fi

  echo "$res"
}

fn-letsencrypt-is-active() {
  declare desc="outputs true if active, false otherwise"
  declare APP=$1
  local domain

  # check if SSL is enabled on per-app level
  if ! is_ssl_enabled "$APP"; then
    echo "false"
    return
  fi

  domain="$(fn-letsencrypt-app-domains "$APP" | xargs | awk '{print $1}')"

  # check if certificate is identical to the current let's encrypt certificate by comparing SHA1 hashes
  local cert_sha1
  if [[ -f "$DOKKU_ROOT/$APP/tls/server.letsencrypt.crt" ]]; then
    cert_sha1=$( (cat "$DOKKU_ROOT/$APP/tls/server.letsencrypt.crt" 2>/dev/null) | sha1sum || echo "not_found")
  else
    cert_sha1=$( (cat "$DOKKU_ROOT/$APP/tls/server.crt" 2>/dev/null) | sha1sum || echo "not_found")
  fi

  local le_sha1="not_found"
  local fileSafeDomain
  fileSafeDomain="${domain/\*/_}" # wildcards are using *.example.com which have certificates named _.example.com
  if [[ -f "$DOKKU_ROOT/$APP/letsencrypt/certs/current/certificates/$fileSafeDomain.pem" ]]; then
    le_sha1=$( (cat "$DOKKU_ROOT/$APP/letsencrypt/certs/current/certificates/$fileSafeDomain.crt" 2>/dev/null) | sha1sum || echo "not_found")
  elif [[ -f "$DOKKU_ROOT/$APP/letsencrypt/certs/current/fullchain.pem" ]]; then
    le_sha1=$( (cat "$DOKKU_ROOT/$APP/letsencrypt/certs/current/fullchain.pem" 2>/dev/null) | sha1sum || echo "not_found")
  fi

  if [[ "$cert_sha1" != "$le_sha1" ]]; then
    echo "false"
    return
  fi

  echo "true"
}

fn-letsencrypt-list-apps-with-expiry() {
  declare desc="list all letsencrypt-secured apps together with their expiry date"
  declare QUIET="${1:-}"

  # prints a tab-separated list of
  #  * app name
  #  * expiry dates as UNIX timestamp (seconds since epoch)
  #  * selected renewal grace period (in seconds)
  #  * time left on certificate (in seconds)
  #  * time until renewal (in seconds)

  # `dokku_apps` warns on stderr when the host has no apps. That is worth
  # surfacing interactively, but not from the daily auto-renew cron job, where
  # an app-less host is an unremarkable state rather than something to report.
  # It reports the empty host by calling `dokku_log_fail`, which exits rather
  # than returns, so the `|| true` has to sit outside the command substitution
  # to keep `set -e` from aborting here.
  local INSTALLED_APPS=""
  if [[ "$QUIET" == "--quiet" ]]; then
    INSTALLED_APPS="$(dokku_apps 2>/dev/null)" || true
  else
    INSTALLED_APPS="$(dokku_apps)" || true
  fi

  for APP in $INSTALLED_APPS; do
    if [[ "$APP" == "=====>" ]] || [[ "$APP" == "My" ]] || [[ "$APP" == "Apps" ]]; then continue; fi
    if [[ "$(fn-letsencrypt-is-active "$APP")" == "true" ]]; then
      local expiry=$(fn-letsencrypt-expiration "$APP")
      local grace_period="$(fn-letsencrypt-computed-graceperiod "$APP")"
      local time_to_expiry=$((expiry - $(date +%s)))
      local time_to_renewal=$((expiry - grace_period - $(date +%s)))
      echo -e "$APP\t$expiry\t$grace_period\t$time_to_expiry\t$time_to_renewal"
    fi
  done
}

fn-letsencrypt-computed-server() {
  declare desc="get configured server"
  declare APP="$1"

  value="$(fn-letsencrypt-server "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-letsencrypt-global-server)"
  fi

  if [[ -z "$value" ]] || [[ "$value" == "default" ]]; then
    value="https://acme-v02.api.letsencrypt.org/directory"
  elif [[ "$value" == "staging" ]]; then
    value="https://acme-staging-v02.api.letsencrypt.org/directory"
  fi

  echo "$value"
}

fn-letsencrypt-global-server() {
  declare desc="get configured server"

  fn-plugin-property-get-default "letsencrypt" "--global" "server" ""
}

fn-letsencrypt-server() {
  declare desc="get configured server"
  declare APP="$1"

  fn-plugin-property-get-default "letsencrypt" "$APP" "server" ""
}

fn-letsencrypt-symlink-certs() {
  declare desc="symlink let's encrypt certificates so they can be found by dokku"
  declare APP="$1" config_dir="$2"

  local app_root="$DOKKU_ROOT/$APP"
  local le_root="$app_root/letsencrypt"
  local domain

  dokku_log_info1 "Installing let's encrypt certificates"

  # link the current config directory to 'current'
  ln -nsf "$config_dir" "$le_root/certs/current"

  # install the let's encrypt certificate for the app
  unset DOKKU_APP_NAME
  domain="$(fn-letsencrypt-app-domains "$APP" | xargs | awk '{print $1}')"
  local fileSafeDomain
  fileSafeDomain="${domain/\*/_}" # wildcards are using *.example.com which have certificates named _.example.com
  dokku certs:add "$APP" "$config_dir/certificates/$fileSafeDomain.pem" "$config_dir/certificates/$fileSafeDomain.key"
  rm -f "$app_root/tls/server.letsencrypt.crt" "$app_root/tls/server.crt"
  cp "$config_dir/certificates/$fileSafeDomain.crt" "$app_root/tls/server.letsencrypt.crt"
  cp "$config_dir/certificates/$fileSafeDomain.crt" "$app_root/tls/server.crt"
}

fn-letsencrypt-report-parse-args() {
  declare desc="strip --format and --global from a report invocation"
  REPORT_FORMAT="stdout"
  REPORT_IS_GLOBAL="false"
  REPORT_ARGS=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --format)
        REPORT_FORMAT="$2"
        shift 2
        ;;
      --global)
        REPORT_IS_GLOBAL="true"
        shift
        ;;
      *)
        REPORT_ARGS+=("$1")
        shift
        ;;
    esac
  done
}

fn-letsencrypt-report-validate-format() {
  declare desc="reject --format when combined with an info flag"
  declare FORMAT="$1" INFO_FLAG="$2"
  if [[ "$FORMAT" != "stdout" ]] && [[ -n "$INFO_FLAG" ]]; then
    dokku_log_fail "--format flag cannot be specified when specifying an info flag"
  fi
}

fn-letsencrypt-report-filter-global() {
  declare desc="rewrite flag_map keeping only --letsencrypt-global-* entries"
  declare flag_map_name="$1"
  local -n flag_map_ref="$flag_map_name"
  local filtered=()
  local flag key
  for flag in "${flag_map_ref[@]}"; do
    key="$(echo "$flag" | cut -d':' -f1)"
    if [[ "$key" == *"-global-"* ]]; then
      filtered+=("$flag")
    fi
  done
  flag_map_ref=("${filtered[@]}")
}

fn-letsencrypt-report-emit-json() {
  declare desc="emit a flag_map as a JSON object, stripping the --letsencrypt- key prefix"
  declare flag_map_name="$1"
  local -n flag_map_ref="$flag_map_name"
  local json_output="{}"
  local flag key value
  for flag in "${flag_map_ref[@]}"; do
    key="$(echo "$flag" | cut -d':' -f1 | sed 's/^--letsencrypt-//')"
    value="$(echo "$flag" | cut -d':' -f2- | sed 's/^ //')"
    json_output="$(echo "$json_output" | jq -c --arg key "$key" --arg value "$value" '. + {($key): $value}')"
  done
  echo "$json_output"
}

fn-letsencrypt-report-add-dns-provider-keys() {
  declare desc="append per-key dns-provider-* rows to flag_map (computed/global/app), redacting values when LETSENCRYPT_REPORT_SANITIZE=true"
  declare flag_map_name="$1" APP="$2"
  local -n flag_map_ref="$flag_map_name"

  local sanitize="${LETSENCRYPT_REPORT_SANITIZE:-false}"
  local line key value
  declare -A global_values=()
  declare -A app_values=()
  declare -A keyset=()

  while IFS= read -r line; do
    [[ -n "$line" ]] || continue
    key="$(cut -d" " -f1 <<<"$line")"
    if [[ "$key" == dns-provider-* ]]; then
      value="$(cut -d" " -f2- <<<"$line")"
      global_values["$key"]="$value"
      keyset["$key"]=1
    fi
  done < <(fn-plugin-property-get-all "letsencrypt" "--global")

  if [[ "$APP" != "--global" ]]; then
    while IFS= read -r line; do
      [[ -n "$line" ]] || continue
      key="$(cut -d" " -f1 <<<"$line")"
      if [[ "$key" == dns-provider-* ]]; then
        value="$(cut -d" " -f2- <<<"$line")"
        app_values["$key"]="$value"
        keyset["$key"]=1
      fi
    done < <(fn-plugin-property-get-all "letsencrypt" "$APP")
  fi

  [[ "${#keyset[@]}" -gt 0 ]] || return 0

  local sorted_key app_value global_value computed_value
  while IFS= read -r sorted_key; do
    app_value="${app_values[$sorted_key]:-}"
    global_value="${global_values[$sorted_key]:-}"
    if [[ -n "$app_value" ]]; then
      computed_value="$app_value"
    else
      computed_value="$global_value"
    fi

    if [[ "$sanitize" == "true" ]]; then
      [[ -n "$app_value" ]] && app_value="****"
      [[ -n "$global_value" ]] && global_value="****"
      [[ -n "$computed_value" ]] && computed_value="****"
    fi

    if [[ -n "$computed_value" ]]; then
      flag_map_ref+=("--letsencrypt-computed-${sorted_key}: ${computed_value}")
    fi
    if [[ -n "$global_value" ]]; then
      flag_map_ref+=("--letsencrypt-global-${sorted_key}: ${global_value}")
    fi
    if [[ -n "$app_value" ]]; then
      flag_map_ref+=("--letsencrypt-${sorted_key}: ${app_value}")
    fi
  done < <(printf '%s\n' "${!keyset[@]}" | sort)
}
