#!/bin/sh
set -eu

DYNAMIC_DIR="/etc/traefik/dynamic"
TLS_CONFIG="${DYNAMIC_DIR}/custom-tls.yml"
CERT_FILE=""
KEY_FILE=""

for candidate in /certs/fullchain.pem /certs/fullchain.crt; do
  if [ -s "$candidate" ]; then
    CERT_FILE="$candidate"
    break
  fi
done

for candidate in /certs/privateKey.pem /certs/privatekey.pem /certs/privkey.pem; do
  if [ -s "$candidate" ]; then
    KEY_FILE="$candidate"
    break
  fi
done

mkdir -p "$DYNAMIC_DIR"
rm -f "$TLS_CONFIG"

if [ -n "$CERT_FILE" ] && [ -n "$KEY_FILE" ]; then
  cat >"$TLS_CONFIG" <<EOF
tls:
  certificates:
    - certFile: ${CERT_FILE}
      keyFile: ${KEY_FILE}
EOF
  echo "Traefik: loaded custom TLS certificate from ${CERT_FILE}"
else
  echo "Traefik: custom TLS certificate not found, falling back to ACME"
fi

exec traefik \
  --providers.file.directory="${DYNAMIC_DIR}" \
  --providers.file.watch=true \
  "$@"
