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

fn-caddy-route-labels() {
  declare desc="emits per-route caddy labels for a non-web container"
  declare APP="$1" PROC_TYPE="$2" STDIN="$3"
  local caddy_domains app_domains output route_proc route_port route_path route_strip
  local matcher_name route_index=0

  app_domains="$(plugn trigger domains-list "$APP")"
  if [[ -n "$app_domains" ]]; then
    caddy_domains="$(echo "$app_domains" | xargs)"
    caddy_domains="${caddy_domains// /, }"
  fi

  output=""
  if [[ -n "$caddy_domains" ]]; then
    # Joining the same site declared by the web container so this container's
    # handler directives are merged into the existing site block by
    # caddy-docker-proxy.
    output="--label 'caddy=${caddy_domains}'"
  fi

  while IFS='|' read -r route_proc route_port route_path route_strip; do
    [[ -z "$route_proc" ]] && continue
    [[ "$route_proc" != "$PROC_TYPE" ]] && continue

    local route_slug
    route_slug="$(fn-caddy-route-slug "$route_path")"
    matcher_name="@${route_slug}"
    # The named matcher accepts both the bare prefix and the prefix-glob form
    # so requests like /api/v0 and /api/v0/users/42 both match.
    output="$output --label 'caddy.${matcher_name}.path=${route_path} ${route_path}/*'"
    output="$output --label 'caddy.${route_index}_route=${matcher_name}'"
    local sub_index=0
    if [[ "$route_strip" == "1" ]]; then
      output="$output --label 'caddy.${route_index}_route.${sub_index}_uri=strip_prefix ${route_path}'"
      sub_index=$((sub_index + 1))
    fi
    output="$output --label \"caddy.${route_index}_route.${sub_index}_reverse_proxy={{upstreams ${route_port}}}\""
    route_index=$((route_index + 1))
  done < <(plugn trigger proxy-routes-list "$APP")

  local proxy_labels_file_path=$(fn-proxy-get-labels-file-path "caddy" "$APP")
  if [[ -f "$proxy_labels_file_path" ]]; then
    while read -r line; do
      [[ -z "$line" ]] && continue
      output="$output --label '$line'"
    done <"$proxy_labels_file_path"
  fi

  echo -n "$STDIN $output"
}

fn-caddy-route-slug() {
  declare desc="returns a deterministic kebab-case slug for a route path"
  declare ROUTE_PATH="$1"
  local s="${ROUTE_PATH#/}"
  s="${s%/}"
  s="${s//\//-}"
  s="${s,,}"
  if [[ -z "$s" ]]; then
    s="root"
  fi
  echo "$s"
}

fn-caddy-logs() {
  declare desc="shows the logs for the caddy container"
  declare TAIL="$1" NUM="$2"
  local dokku_logs_args=("--tail" "$NUM")

  if [[ "$TAIL" == "true" ]]; then
    dokku_logs_args+=("--follow")
  fi

  "$DOCKER_BIN" logs caddy-caddy-1 "${dokku_logs_args[@]}"
}

fn-caddy-logs-usage() {
  declare desc="logs specific usage"
  echo "Usage: dokku caddy:logs"
  echo " display recent caddy log output"
  echo ""
  echo " -n, --num NUM        # the number of lines to display"
  echo " -t, --tail           # continually stream logs"
}

fn-caddy-template-compose-file() {
  declare desc="templates out the compose file"
  declare OUTPUT_PATH="$1"
  local COMPOSE_TEMPLATE="$PLUGIN_AVAILABLE_PATH/caddy-vhosts/templates/compose.yml.sigil"

  CUSTOM_COMPOSE_TEMPLATE="$(plugn trigger caddy-template-source "$APP")"
  if [[ -n "$CUSTOM_COMPOSE_TEMPLATE" ]]; then
    COMPOSE_TEMPLATE="$CUSTOM_COMPOSE_TEMPLATE"
  fi

  local SIGIL_PARAMS=(CADDY_DATA_DIR="${DOKKU_LIB_ROOT}/data/caddy"
    CADDY_IMAGE="$(fn-caddy-computed-image)"
    CADDY_LETSENCRYPT_EMAIL="$(fn-caddy-computed-letsencrypt-email)"
    CADDY_LETSENCRYPT_SERVER="$(fn-caddy-computed-letsencrypt-server)"
    CADDY_LOG_LEVEL="$(fn-caddy-computed-log-level)"
    CADDY_POLLING_INTERVAL="$(fn-caddy-computed-polling-interval)")

  sigil -f "$COMPOSE_TEMPLATE" "${SIGIL_PARAMS[@]}" | cat -s >"$OUTPUT_PATH"
}

fn-caddy-global-image() {
  fn-plugin-property-get-default "caddy" "--global" "image" ""
}

fn-caddy-computed-image() {
  local value
  value="$(fn-caddy-global-image)"
  if [[ -z "$value" ]]; then
    value="$(grep "FROM" "$PLUGIN_AVAILABLE_PATH/caddy-vhosts/Dockerfile" | awk '{print $2}')"
  fi
  echo "$value"
}

fn-caddy-global-letsencrypt-email() {
  fn-plugin-property-get-default "caddy" "--global" "letsencrypt-email" ""
}

fn-caddy-computed-letsencrypt-email() {
  fn-caddy-global-letsencrypt-email
}

fn-caddy-global-letsencrypt-server() {
  fn-plugin-property-get-default "caddy" "--global" "letsencrypt-server" ""
}

fn-caddy-computed-letsencrypt-server() {
  local value
  value="$(fn-caddy-global-letsencrypt-server)"
  if [[ -z "$value" ]]; then
    value="https://acme-v02.api.letsencrypt.org/directory"
  fi
  echo "$value"
}

fn-caddy-global-log-level() {
  fn-plugin-property-get-default "caddy" "--global" "log-level" ""
}

fn-caddy-computed-log-level() {
  local value
  value="$(fn-caddy-global-log-level)"
  if [[ -z "$value" ]]; then
    value="ERROR"
  fi
  echo "${value^^}"
}

fn-caddy-global-polling-interval() {
  fn-plugin-property-get-default "caddy" "--global" "polling-interval" ""
}

fn-caddy-computed-polling-interval() {
  local value
  value="$(fn-caddy-global-polling-interval)"
  if [[ -z "$value" ]]; then
    value="5s"
  fi
  echo "$value"
}

fn-caddy-tls-internal() {
  declare APP="$1"
  fn-plugin-property-get-default "caddy" "$APP" "tls-internal" ""
}

fn-caddy-computed-tls-internal() {
  declare APP="$1"
  local value
  value="$(fn-caddy-tls-internal "$APP")"
  if [[ -z "$value" ]]; then
    value="$(fn-caddy-global-tls-internal)"
  fi
  if [[ -z "$value" ]]; then
    value="false"
  fi
  echo "$value"
}

fn-caddy-global-tls-internal() {
  fn-plugin-property-get-default "caddy" "--global" "tls-internal" ""
}
