#!/bin/sh
set -eu

if [ -n "${VAULT_ENV_FILE:-}" ]; then
  if [ -f "${VAULT_ENV_FILE}" ]; then
    # shellcheck disable=SC1090
    . "${VAULT_ENV_FILE}"
  else
    echo "Vault env file not found: ${VAULT_ENV_FILE}" >&2
    exit 1
  fi
fi

if [ -n "${VAULT_COPY_FILES:-}" ]; then
  old_ifs="$IFS"
  IFS=','
  for pair in ${VAULT_COPY_FILES}; do
    src="${pair%%:*}"
    dest="${pair#*:}"
    if [ -z "${src}" ] || [ -z "${dest}" ]; then
      echo "Vault copy entry malformed: ${pair}" >&2
      exit 1
    fi
    if [ ! -f "${src}" ]; then
      echo "Vault file not found: ${src}" >&2
      exit 1
    fi
    mkdir -p "$(dirname "${dest}")"
    cp "${src}" "${dest}"
  done
  IFS="$old_ifs"
fi

if [ -d /app/venv/bin ]; then
  PATH="/app/venv/bin:$PATH"
  export PATH
fi

if [ "${MAILU_POSTFIX_DISABLE_POSTLOG_UNIX_DGRAM:-}" = "true" ] || { [ -x /usr/sbin/postfix ] && [ -x /usr/sbin/postconf ]; }; then
  mkdir -p /tmp/mailu-wrapper-bin
  cat > /tmp/mailu-wrapper-bin/postfix <<'EOF'
#!/bin/sh
if [ "${1:-}" = "start-fg" ]; then
  /usr/sbin/postconf -MX postlog/unix-dgram 2>/dev/null || true
  exec /usr/libexec/postfix/master -c /etc/postfix -d
fi
exec /usr/sbin/postfix "$@"
EOF
  chmod 0755 /tmp/mailu-wrapper-bin/postfix
  PATH="/tmp/mailu-wrapper-bin:$PATH"
  export PATH
fi

exec "$@"
