-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc2fb2.sh
More file actions
executable file
·619 lines (528 loc) · 22.4 KB
/
Copy pathdoc2fb2.sh
File metadata and controls
executable file
·619 lines (528 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#!/usr/bin/env bash
# doc2fb2.sh — DOC/DOCX/RTF/ODT -> FB2 (recursive), SINGLE-THREAD
# JSONL log (real actions + errors), progress per line (+percent), log-level filtering
set -u
###############################################################################
# SCRIPT ID / PATHS
###############################################################################
SCRIPT_NAME="$(basename -- "$0")"
SCRIPT_BASE="${SCRIPT_NAME%.*}"
SCRIPT_DIR="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
LOG_TEMPLATE_FILE="${SCRIPT_DIR}/conf/log_template.conf"
if [[ -r "${LOG_TEMPLATE_FILE}" ]]; then
# shellcheck source=/dev/null
source "${LOG_TEMPLATE_FILE}"
fi
LOG_SCHEMA_VERSION="${LOG_SCHEMA_VERSION:-1.0}"
LOG_COMPAT_TARGETS="${LOG_COMPAT_TARGETS:-elk,opensearch,loki,graylog,splunk}"
usage() {
cat <<'EOF'
doc2fb2.sh — конвертация DOC/DOCX/RTF/ODT -> FB2 (рекурсивно), ОДНОПОТОЧНО
Прогресс:
Одна строка на каждый найденный файл:
[i/total | P%] OK|DRY|SKIP|FAIL src -> out (detail)
Лог (JSONL):
По умолчанию пишем реальные действия и ошибки.
Пропуски (SKIP/exists/skip-newer) и dry-run — в лог НЕ пишутся.
Можно ограничить лог только ошибками: --log-level error
Использование:
doc2fb2.sh -d DIR [опции]
Опции:
-d, --dir DIR
-o, --out OUTDIR
-l, --log LOGFILE
-n, --dry-run
--overwrite
--skip-newer (только вместе с --overwrite)
--exclude PATTERN (можно несколько раз; сравнение с basename)
--only doc|docx|rtf|odt|all
--author NAME
--title-mode auto|filename|keep
--toc / --no-toc
--toc-depth N
--log-level info|error (по умолчанию: info)
--debug
-h, --help
Pipeline:
docx -> pandoc -> fb2
odt -> pandoc -> fb2
doc/rtf -> LibreOffice -> odt -> pandoc -> fb2
Если LO не смог загрузить документ — fallback:
- rtf: pandoc напрямую; затем unrtf -> txt -> pandoc (если unrtf есть)
- doc: если mime=text/html -> pandoc html -> fb2
иначе antiword/catdoc/catdoc -b/wvText -> txt -> pandoc (что доступно)
Автоудаление логов:
Удаляет doc2fb2_*.jsonl старше 10 дней рядом с логом.
EOF
}
ts() { date '+%Y-%m-%d %H:%M:%S'; }
json_escape() {
awk 'BEGIN{ORS=""; first=1}
{
if(!first) printf "\\n";
first=0;
gsub(/\\/,"\\\\");
gsub(/"/,"\\\"");
gsub(/\t/,"\\t");
gsub(/\r/,"\\r");
printf "%s",$0;
}'
}
log_json() {
local level="$1" event="$2" src="${3:-}" out="${4:-}" msg="${5:-}" detail="${6:-}"
local level_norm _ts src_esc out_esc msg_esc detail_esc
level_norm="$(printf '%s' "${level}" | tr '[:upper:]' '[:lower:]')"
_ts="$(ts)"
src_esc="$(printf '%s' "${src}" | json_escape)"
out_esc="$(printf '%s' "${out}" | json_escape)"
msg_esc="$(printf '%s' "${msg}" | json_escape)"
detail_esc="$(printf '%s' "${detail}" | json_escape)"
printf '{"@timestamp":"%s","schema.version":"%s","compat.targets":"%s","log.level":"%s","message":"%s","event.action":"%s","service.name":"%s","script":"%s","event":"%s","level":"%s","src":"%s","out":"%s","msg":"%s","detail":"%s","pid":%s}\n' \
"${_ts}" "${LOG_SCHEMA_VERSION}" "${LOG_COMPAT_TARGETS}" "${level_norm}" "${msg_esc}" "${event}" "${SCRIPT_BASE}" "${SCRIPT_NAME}" "${event}" "${level_norm}" \
"${src_esc}" \
"${out_esc}" \
"${msg_esc}" \
"${detail_esc}" \
"$$" >> "${LOGFILE}"
}
# log-level filtering:
# LOG_LEVEL=info -> writes info + error
# LOG_LEVEL=error -> writes only error
log_info() {
[[ "${LOG_LEVEL:-info}" = "error" ]] && return 0
log_json "info" "$1" "${2:-}" "${3:-}" "${4:-}" "${5:-}"
}
log_error() {
log_json "error" "$1" "${2:-}" "${3:-}" "${4:-}" "${5:-}"
}
have_cmd() { command -v "$1" >/dev/null 2>&1; }
###############################################################################
# Args / defaults
###############################################################################
DIR=""
OUTDIR=""
LOGFILE=""
DRYRUN=0
OVERWRITE=0
SKIP_NEWER=0
AUTHOR_SET=0
AUTHOR="${USER:-}"
TITLE_MODE="auto"
TOC=1
TOC_DEPTH=3
ONLY="all"
EXCLUDES=()
LOG_LEVEL="info" # info|error
DEBUG=0
ORIG_ARGS=("$@")
while [[ $# -gt 0 ]]; do
case "$1" in
-h|--help) usage; exit 0 ;;
--debug) DEBUG=1; shift ;;
-d|--dir) DIR="${2:-}"; shift 2 ;;
-o|--out) OUTDIR="${2:-}"; shift 2 ;;
-l|--log) LOGFILE="${2:-}"; shift 2 ;;
-n|--dry-run) DRYRUN=1; shift ;;
--overwrite) OVERWRITE=1; shift ;;
--skip-newer) SKIP_NEWER=1; shift ;;
--author) AUTHOR_SET=1; AUTHOR="${2:-}"; shift 2 ;;
--title-mode) TITLE_MODE="${2:-}"; shift 2 ;;
--toc) TOC=1; shift ;;
--no-toc) TOC=0; shift ;;
--toc-depth) TOC_DEPTH="${2:-}"; shift 2 ;;
--only) ONLY="${2:-}"; shift 2 ;;
--exclude) EXCLUDES+=( "${2:-}" ); shift 2 ;;
--log-level) LOG_LEVEL="${2:-}"; shift 2 ;;
--) shift; break ;;
-*) echo "Неизвестная опция: $1" >&2; exit 2 ;;
*) break ;;
esac
done
if [[ "${DEBUG}" -eq 1 ]]; then
echo "DEBUG:"
echo " script: $0"
echo " orig args count: ${#ORIG_ARGS[@]}"
for i in "${!ORIG_ARGS[@]}"; do printf ' arg[%d]=<%s>\n' "${i}" "${ORIG_ARGS[${i}]}"; done
echo " parsed DIR=<${DIR}>"
echo " parsed OUTDIR=<${OUTDIR}>"
echo " parsed LOGFILE=<${LOGFILE}>"
echo " DRYRUN=${DRYRUN} OVERWRITE=${OVERWRITE} SKIP_NEWER=${SKIP_NEWER}"
echo " ONLY=${ONLY} TITLE_MODE=${TITLE_MODE} TOC=${TOC} TOC_DEPTH=${TOC_DEPTH}"
echo " LOG_LEVEL=${LOG_LEVEL}"
echo " EXCLUDES count=${#EXCLUDES[@]}"
exit 0
fi
###############################################################################
# Validate / deps
###############################################################################
[[ -n "${DIR:-}" ]] || { echo "Ошибка: не указан -d/--dir" >&2; usage; exit 2; }
[[ -d "${DIR}" ]] || { echo "Ошибка: DIR не каталог: ${DIR}" >&2; exit 2; }
case "${ONLY}" in all|doc|docx|rtf|odt) ;; *) echo "Ошибка: --only all|doc|docx|rtf|odt" >&2; exit 2 ;; esac
if [[ "${SKIP_NEWER}" -eq 1 ]] && [[ "${OVERWRITE}" -eq 0 ]]; then
echo "Ошибка: --skip-newer работает только вместе с --overwrite" >&2
exit 2
fi
case "${LOG_LEVEL}" in
info|error) ;;
*) echo "Ошибка: --log-level должен быть info или error" >&2; exit 2 ;;
esac
have_cmd find || { echo "Ошибка: find не найден" >&2; exit 3; }
have_cmd pandoc || { echo "Ошибка: pandoc не найден" >&2; exit 3; }
have_cmd awk || { echo "Ошибка: awk не найден" >&2; exit 3; }
have_cmd unzip || { echo "Ошибка: unzip не найден (нужен для метаданных docx)" >&2; exit 3; }
if have_cmd soffice; then LO_CMD="soffice"
elif have_cmd libreoffice; then LO_CMD="libreoffice"
else LO_CMD=""
fi
DIR="$(cd "${DIR}" 2>/dev/null && pwd)" || { echo "Ошибка: не могу открыть каталог: ${DIR}" >&2; exit 2; }
if [[ -n "${OUTDIR:-}" ]]; then
mkdir -p "${OUTDIR}" 2>/dev/null || { echo "Ошибка: не могу создать OUTDIR: ${OUTDIR}" >&2; exit 2; }
OUTDIR="$(cd "${OUTDIR}" 2>/dev/null && pwd)" || { echo "Ошибка: не могу открыть OUTDIR: ${OUTDIR}" >&2; exit 2; }
fi
if [[ -z "${LOGFILE:-}" ]]; then
LOGFILE="./doc2fb2_$(date '+%Y-%m-%d').jsonl"
fi
mkdir -p "$(dirname "${LOGFILE}")" 2>/dev/null || { echo "Ошибка: не могу создать каталог лога" >&2; exit 2; }
###############################################################################
# Auto-delete old logs (keep 10 days)
###############################################################################
cleanup_old_logs() {
local keep_days=10
local logdir cur pattern
logdir="$(cd "$(dirname "${LOGFILE}")" 2>/dev/null && pwd)" || return 0
cur="${logdir}/$(basename "${LOGFILE}")"
pattern="doc2fb2_*.jsonl"
log_info "log_cleanup_start" "" "" "Очистка логов старше 10 дней" "dir=${logdir} pattern=${pattern} keep_days=${keep_days}"
local _log_list_file
_log_list_file="$(mktemp)"
find "${logdir}" -maxdepth 1 -type f -name "${pattern}" -mtime +"${keep_days}" -print0 2>/dev/null > "${_log_list_file}"
while IFS= read -r -d '' f; do
[[ "${f}" = "${cur}" ]] && continue
if rm -f -- "${f}" 2>/dev/null; then
log_info "log_cleanup_deleted" "${f}" "" "Удалён старый лог" "keep_days=${keep_days}"
else
log_error "log_cleanup_failed" "${f}" "" "Не удалось удалить старый лог" "keep_days=${keep_days}"
fi
done < "${_log_list_file}"
rm -f -- "${_log_list_file}"
log_info "log_cleanup_done" "" "" "Очистка логов завершена" ""
}
cleanup_old_logs
###############################################################################
# Helpers
###############################################################################
matches_excludes() {
local bn="$1" p
for p in "${EXCLUDES[@]}"; do
[[ "${bn}" == "${p}" ]] && return 0
done
return 1
}
only_allows_ext() {
local ext="${1,,}"
[[ "${ONLY}" = "all" ]] && return 0
[[ "${ext}" == "${ONLY}" ]]
}
title_from_filename() {
local f="$1" b name
b="$(basename "${f}")"
name="${b%.*}"
name="${name//_/ }"
name="${name//-/ }"
name="$(printf '%s' "${name}" | awk '{$1=$1;print}')"
printf '%s' "${name}"
}
extract_docx_meta() {
local docx="$1"
unzip -p "${docx}" docProps/core.xml 2>/dev/null | awk '
BEGIN{ s=""; }
{ s = s $0 "\n"; }
END{
title=""; creator="";
if (match(s, /<dc:title[^>]*>([^<]*)<\/dc:title>/, m)) title=m[1];
if (match(s, /<dc:creator[^>]*>([^<]*)<\/dc:creator>/, n)) creator=n[1];
gsub(/^[[ \t\r\n]+/, "", title); gsub(/[[ \t\r\n]+$/, "", title);
gsub(/^[[ \t\r\n]+/, "", creator); gsub(/[[ \t\r\n]+$/, "", creator);
printf "%s\t%s", title, creator;
}' || true
}
make_out_path() {
local src="$1" base name rel rel_dir
base="$(basename "${src}")"
name="${base%.*}"
if [[ -n "${OUTDIR:-}" ]] && [[ "${src}" == "${DIR}/"* ]]; then
rel="${src#"${DIR}"/}"
rel_dir="$(dirname "${rel}")"
printf '%s/%s/%s.fb2\n' "${OUTDIR}" "${rel_dir}" "${name}"
elif [[ -n "${OUTDIR:-}" ]]; then
printf '%s/%s.fb2\n' "${OUTDIR}" "${name}"
else
printf '%s/%s.fb2\n' "$(dirname "${src}")" "${name}"
fi
}
ensure_outdir_for() { mkdir -p "$(dirname "$1")" 2>/dev/null; }
url_escape_path() {
local s="$1"
s="${s//%/%25}"
s="${s//#/%23}"
s="${s// /%20}"
printf '%s' "${s}"
}
lo_has_error() { grep -q '^Error:' "$1" 2>/dev/null; }
get_mime() {
if have_cmd file; then
file -b --mime-type -- "$1" 2>/dev/null || true
else
printf ''
fi
}
run_pandoc_to_fb2() {
local in="$1" fmt="$2" src="$3" out="$4" errfile="$5"
local -a meta toc fmtarg
meta=(); toc=(); fmtarg=()
[[ "${TOC}" -eq 1 ]] && toc+=( "--toc" "--toc-depth=${TOC_DEPTH}" )
[[ -n "${fmt}" ]] && fmtarg=( -f "${fmt}" )
local meta_title="" meta_creator="" ttitle="" tauthor=""
if [[ "${in,,}" == *.docx ]]; then
IFS=$'\t' read -r meta_title meta_creator < <(extract_docx_meta "${in}" || true)
fi
case "${TITLE_MODE}" in
auto)
if [[ -n "${meta_title}" ]]; then ttitle="${meta_title}"; else ttitle="$(title_from_filename "${src}")"; fi
meta+=( "--metadata" "title=${ttitle}" )
;;
filename)
ttitle="$(title_from_filename "${src}")"
meta+=( "--metadata" "title=${ttitle}" )
;;
keep) ;;
*)
log_error "stage_failed" "${src}" "${out}" "Некорректный --title-mode" "value=${TITLE_MODE}"
return 2
;;
esac
if [[ "${AUTHOR_SET}" -eq 1 ]]; then
tauthor="${AUTHOR}"
else
if [[ -n "${meta_creator}" ]]; then tauthor="${meta_creator}"
elif [[ -n "${USER:-}" ]]; then tauthor="${USER}"
else tauthor=""
fi
fi
[[ -n "${tauthor}" ]] && meta+=( "--metadata" "author=${tauthor}" )
if pandoc "${fmtarg[@]}" "${in}" -o "${out}" "${meta[@]}" "${toc[@]}" >>"${errfile}" 2>&1; then
log_info "ok" "${src}" "${out}" "Успешно" ""
return 0
else
rm -f "${out}" >/dev/null 2>&1 || true
log_error "pandoc_failed" "${src}" "${out}" "Ошибка pandoc" "tail_err=$(tail -n 240 "${errfile}" 2>/dev/null || true)"
return 1
fi
}
fallback_convert() {
local src="$1" out="$2" ext="$3" workdir="$4" errfile="$5"
local mime txt
mime="$(get_mime "${src}")"
log_info "fallback_start" "${src}" "${out}" "Пробуем fallback без LibreOffice" "ext=${ext,,} mime=${mime:-unknown}"
if [[ "${ext,,}" == "rtf" ]]; then
run_pandoc_to_fb2 "${src}" "" "${src}" "${out}" "${errfile}" && return 0
if have_cmd unrtf; then
txt="${workdir}/fallback.txt"
if unrtf --text --nopict --quiet -- "${src}" >"${txt}" 2>>"${errfile}"; then
run_pandoc_to_fb2 "${txt}" "plain" "${src}" "${out}" "${errfile}" && return 0
fi
fi
log_error "fallback_failed" "${src}" "${out}" "Fallback не помог для RTF" "mime=${mime:-unknown}; tail_err=$(tail -n 120 "${errfile}" 2>/dev/null || true)"
return 1
fi
if [[ "${ext,,}" == "doc" ]]; then
if [[ "${mime}" == "text/html" || "${mime}" == "application/xhtml+xml" ]]; then
run_pandoc_to_fb2 "${src}" "html" "${src}" "${out}" "${errfile}" && return 0
fi
txt="${workdir}/fallback.txt"
if have_cmd antiword; then
if antiword "${src}" >"${txt}" 2>>"${errfile}"; then
run_pandoc_to_fb2 "${txt}" "plain" "${src}" "${out}" "${errfile}" && return 0
fi
fi
if have_cmd catdoc; then
if catdoc "${src}" >"${txt}" 2>>"${errfile}"; then
run_pandoc_to_fb2 "${txt}" "plain" "${src}" "${out}" "${errfile}" && return 0
fi
if catdoc -b "${src}" >"${txt}" 2>>"${errfile}"; then
run_pandoc_to_fb2 "${txt}" "plain" "${src}" "${out}" "${errfile}" && return 0
fi
fi
if have_cmd wvText; then
if wvText "${src}" "${txt}" >>"${errfile}" 2>&1; then
[[ -s "${txt}" ]] && run_pandoc_to_fb2 "${txt}" "plain" "${src}" "${out}" "${errfile}" && return 0
fi
fi
log_error "fallback_failed" "${src}" "${out}" "Fallback не помог для DOC" \
"mime=${mime:-unknown}; have_antiword=$(have_cmd antiword && echo 1 || echo 0 || true); have_catdoc=$(have_cmd catdoc && echo 1 || echo 0 || true); have_wvText=$(have_cmd wvText && echo 1 || echo 0 || true); tail_err=$(tail -n 200 "${errfile}" 2>/dev/null || true)"
return 1
fi
log_error "fallback_failed" "${src}" "${out}" "Fallback не настроен для этого типа" "ext=${ext,,} mime=${mime:-unknown}"
return 1
}
short_fail_reason() {
local errfile="$1"
local s
s="$(grep -m1 '^Error:' "${errfile}" 2>/dev/null || true)"
[[ -n "${s}" ]] && printf '%s' "${s}" && return 0
tail -n 1 "${errfile}" 2>/dev/null || true
}
convert_one() {
# prints: STATUS|DETAIL|SRC|OUT
local src="$1"
local base ext out
local tmproot workdir errfile staged_docx staged_odt produced produced2
local detail=""
base="$(basename "${src}")"
ext="${src##*.}"
out="$(make_out_path "${src}")"
if matches_excludes "${base}"; then echo "SKIP|excluded|${src}|${out}"; return 0; fi
if ! only_allows_ext "${ext}"; then echo "SKIP|filtered|${src}|${out}"; return 0; fi
case "${base}" in "~$"*) echo "SKIP|tempfile|${src}|${out}"; return 0 ;; *) ;; esac
if [[ -e "${out}" ]]; then
if [[ "${OVERWRITE}" -eq 0 ]]; then echo "SKIP|exists|${src}|${out}"; return 0; fi
if [[ "${SKIP_NEWER}" -eq 1 ]] && ! [[ "${src}" -nt "${out}" ]]; then echo "SKIP|skip-newer|${src}|${out}"; return 0; fi
fi
if [[ "${DRYRUN}" -eq 1 ]]; then echo "DRY||${src}|${out}"; return 0; fi
ensure_outdir_for "${out}"
tmproot="${TMPDIR:-/tmp}/doc2fb2.$$.${RANDOM}"
workdir="${tmproot}/work"
mkdir -p "${workdir}" 2>/dev/null || {
log_error "stage_failed" "${src}" "${out}" "Не удалось создать временный каталог" "tmp=${workdir}"
echo "FAIL|tmpdir|${src}|${out}"
return 0
}
errfile="${workdir}/err.txt"; : > "${errfile}"
staged_docx="${workdir}/staged.docx"
staged_odt="${workdir}/staged.odt"
local lo_profile="${tmproot}/lo_profile"
mkdir -p "${lo_profile}" 2>/dev/null || true
local lo_uri
lo_uri="file://$(url_escape_path "${lo_profile}")"
if [[ "${ext,,}" == "docx" ]]; then
cp -f "${src}" "${staged_docx}" >>"${errfile}" 2>&1 || {
log_error "stage_failed" "${src}" "${out}" "Не удалось подготовить .docx" "tail_err=$(tail -n 120 "${errfile}" 2>/dev/null || true)"
echo "FAIL|stage-docx|${src}|${out}"
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
}
log_info "docx_to_fb2_start" "${src}" "${out}" "docx -> fb2 (pandoc)" ""
if run_pandoc_to_fb2 "${staged_docx}" "" "${src}" "${out}" "${errfile}"; then
echo "OK||${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|pandoc:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
if [[ "${ext,,}" == "odt" ]]; then
cp -f "${src}" "${staged_odt}" >>"${errfile}" 2>&1 || {
log_error "stage_failed" "${src}" "${out}" "Не удалось подготовить .odt" "tail_err=$(tail -n 120 "${errfile}" 2>/dev/null || true)"
echo "FAIL|stage-odt|${src}|${out}"
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
}
log_info "odt_to_fb2_start" "${src}" "${out}" "odt -> fb2 (pandoc)" ""
if run_pandoc_to_fb2 "${staged_odt}" "" "${src}" "${out}" "${errfile}"; then
echo "OK||${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|pandoc:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
if [[ "${ext,,}" == "doc" || "${ext,,}" == "rtf" ]]; then
if [[ -z "${LO_CMD:-}" ]]; then
log_error "to_odt_failed" "${src}" "${out}" "LibreOffice не найден" "rc=127"
if fallback_convert "${src}" "${out}" "${ext}" "${workdir}" "${errfile}"; then
echo "OK|fallback|${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|fallback:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
log_info "to_odt_start" "${src}" "${out}" "LO -> odt" "ext=${ext,,}"
"${LO_CMD}" -env:UserInstallation="${lo_uri}" --headless --convert-to odt --outdir "${workdir}" "${src}" >>"${errfile}" 2>&1
local lo_rc=$?
produced="${workdir}/${base%.*}.odt"
[[ ! -f "${produced}" ]] && produced="$({ find "${workdir}" -maxdepth 1 -type f -name '*.odt' -printf '%T@|%p\n' 2>/dev/null | sort -nr | awk -F'|' 'NR == 1 { print $2 }'; } || true)"
if [[ -z "${produced:-}" ]] || [[ ! -f "${produced}" ]] || lo_has_error "${errfile}"; then
log_error "to_odt_failed" "${src}" "${out}" "Не удалось получить .odt" "rc=${lo_rc}; tail_err=$(tail -n 160 "${errfile}" 2>/dev/null || true)"
: > "${errfile}"
log_info "to_docx_alt_start" "${src}" "${out}" "LO -> docx (alt)" ""
"${LO_CMD}" -env:UserInstallation="${lo_uri}" --headless --convert-to docx --outdir "${workdir}" "${src}" >>"${errfile}" 2>&1
produced2="${workdir}/${base%.*}.docx"
[[ ! -f "${produced2}" ]] && produced2="$({ find "${workdir}" -maxdepth 1 -type f -name '*.docx' -printf '%T@|%p\n' 2>/dev/null | sort -nr | awk -F'|' 'NR == 1 { print $2 }'; } || true)"
if [[ -n "${produced2:-}" ]] && [[ -f "${produced2}" ]] && ! lo_has_error "${errfile}"; then
cp -f "${produced2}" "${staged_docx}" >>"${errfile}" 2>&1 || true
log_info "to_docx_alt_ok" "${src}" "${out}" "Получен .docx (alt)" "produced=${produced2}"
if run_pandoc_to_fb2 "${staged_docx}" "" "${src}" "${out}" "${errfile}"; then
echo "OK|lo-docx-alt|${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|pandoc:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
if fallback_convert "${src}" "${out}" "${ext}" "${workdir}" "${errfile}"; then
echo "OK|fallback|${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|fallback:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
cp -f "${produced}" "${staged_odt}" >>"${errfile}" 2>&1 || {
log_error "stage_failed" "${src}" "${out}" "Не удалось подготовить .odt для pandoc" "tail_err=$(tail -n 120 "${errfile}" 2>/dev/null || true)"
echo "FAIL|stage-odt|${src}|${out}"
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
}
log_info "to_odt_ok" "${src}" "${out}" "Получен .odt" "produced=${produced} rc=${lo_rc}"
if run_pandoc_to_fb2 "${staged_odt}" "" "${src}" "${out}" "${errfile}"; then
echo "OK||${src}|${out}"
else
detail="$(short_fail_reason "${errfile}")"
echo "FAIL|pandoc:${detail:0:140}|${src}|${out}"
fi
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
fi
echo "SKIP|unsupported|${src}|${out}"
rm -rf "${tmproot}" >/dev/null 2>&1 || true
return 0
}
###############################################################################
# Main loop (single-thread)
###############################################################################
log_info "scan_start" "${DIR}" "" "Старт" "log=${LOGFILE} dryrun=${DRYRUN} overwrite=${OVERWRITE} skip_newer=${SKIP_NEWER} only=${ONLY} excludes_count=${#EXCLUDES[@]} author_set=${AUTHOR_SET} author=${AUTHOR} title_mode=${TITLE_MODE} toc=${TOC} toc_depth=${TOC_DEPTH} log_level=${LOG_LEVEL}"
TOTAL="$({ find "${DIR}" -type f \( -iname '*.doc' -o -iname '*.docx' -o -iname '*.rtf' -o -iname '*.odt' \) -print | wc -l | awk '{print $1}'; } || true)"
case "${TOTAL}" in ''|*[!0-9]*) TOTAL=0 ;; *) ;; esac
[[ "${TOTAL}" -gt 0 ]] || TOTAL=1
i=0
while IFS= read -r -d '' f; do
i=$((i+1))
pct=$(( i * 100 / TOTAL ))
line="$(convert_one "${f}")"
status="${line%%|*}"
rest="${line#*|}"
detail="${rest%%|*}"
rest2="${rest#*|}"
src="${rest2%%|*}"
out="${rest2#*|}"
printf '[%6d/%-6d | %3d%%] %-4s %s -> %s' "${i}" "${TOTAL}" "${pct}" "${status}" "${src}" "${out}"
[[ -n "${detail}" ]] && printf ' (%s)' "${detail}"
printf '\n'
done < <(find "${DIR}" -type f \( -iname '*.doc' -o -iname '*.docx' -o -iname '*.rtf' -o -iname '*.odt' \) -print0 || true)
echo "Готово. Лог: ${LOGFILE}"