[go: up one dir, main page]

File: daps.in

package info (click to toggle)
daps 3.3.2%2Bcleaned1-6.1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 5,484 kB
  • sloc: xml: 9,773; sh: 3,059; python: 1,322; lisp: 380; makefile: 240
file content (1778 lines) | stat: -rwxr-xr-x 64,937 bytes parent folder | download | duplicates (3)
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
#!/bin/bash
#
# Copyright (C) 2012-2020 SUSE Software Solutions Germany GmbH
#
# Author:
# Frank Sundermeyer <fsundermeyer at opensuse dot org>
#
# DAPS = DocBook Authoring and Publishing Suite

MY_NAME=DAPS
VERSION=@PACKAGE_VERSION@
MY_URL=https://opensuse.github.io/daps

export MY_NAME VERSION MY_URL

# autoconf replaces @foo@ stuff with ${prefix}/.. if @foo@ has not
# explicitly been set, so we need to at least export prefix to
# be on the safe side

export prefix=@prefix@

#
# Do not even attempt to start, if we are in a directory that does not exist
# (fix for https://bugzilla.suse.com/show_bug.cgi?id=961526)

[[ -d $(pwd 2>/dev/null) ]] || {
    echo "Cannot operate from a directory that does not exist!"
    exit 1
    }

# ----------------------------------------------------------------------------
# VARIABLES
#
# First, list all variables we need to pass to make. They all need to be
# EXPORTED, but we do not want to write the export statement in the config
# files, so we need to have this list
#
# IMPORTANT
# All variables that need to be exported for further use in the makefiles
# need to be added here!!
#


# PENDING:
# DISTVER, PRODUCTNAME, and PRODUCTNAMEREG are only need for resolving the
# suse-PIs. Once we get rid of that, remove these variables from the list
#

# TODO fs 2012-12-20:
# A lot of variables get exported in lib/daps_functions _and_ here - this is
# not necessary. Clean up!

declare -a VARLIST
VARLIST=(
    ADOC_ATTRIBUTES
    ADOC_BACKEND
    ADOC_FAILURE_LEVEL
    ADOC_IMG_DIR
    ADOC_POST
    ADOC_POST_STYLE
    ADOC_SET_STYLE
    ADOC_SET
    ADOC_TYPE
    ASCIIDOC
    SPELL_CHECKER
    SPELL_EXTRA_DICT
    SPELL_LANG
    SPELL_SKIP_TAGS
    BUILD_DIR
    CB_OPTIONS
    CHECK_WELLFORMED
    COLOR
    COMMENTS
    COMMENT_STR
    CONF_PREFIX
    CONVERT_OPTS_JPG
    CONVERT_OPTS_PNG
    CROPMARKS
    DB5TODB4
    DB5TODB4NH
    DBNOCONV
    DEBUG
    DISTVER
    DOC_DIR
    DAPS_CONFIG_FILE
    DAPSROOT
    DAPSROOT_DEFAULT
    DEF_FILE
    DESKTOPFILES
    DEVEL
    DIA_OPTIONS
    DOCBOOK4_PROFILE_URN
    DOCBOOK4_STYLE_URI
    DOCBOOK5_PROFILE_URN
    DOCBOOK5_RNG
    DOCBOOK5_RNG_URI
    DOCBOOK5_STYLE_URI
    DOCBOOK_STYLES
    DOCBOOK_VERSION
    DOCCONF
    DOCCONF_DEFAULT
    DOCUMENTFILES
    DRAFT
    DRAFT_STR
    EPUB3
    EPUB_CSS
    EXPORT_DIR
    FALLBACK_STYLEROOT
    FOP_CONFIG_FILE
    FOP_CMD_OPTIONS
    FOP_JAVA_FLAGS
    FOP_JAVA_JARS
    FOP_JAVA_OPTIONS
    FOP_WRAPPER
    FORCE_REBUILD
    FORMATTER
    GRAYSCALE
    GZIP_MAN
    HTML5
    HTML_CSS
    HTMLSINGLE
    IMAGES_COLOR
    IMG_VIEWER
    INCLUDE_MANIFEST
    INK_OPTIONS
    JING_JAVA_FLAGS
    JING_JAVA_JARS
    JING_JAVA_OPTIONS
    JING_WRAPPER
    LEAN
    LIB_DIR
    LIBEXEC_DIR
    LOG_DIR
    MAIN
    META
    META_STR
    NAME
    NODC
    NOENT
    NOEPUB
    NOGZIP
    NOHTML
    NOIMG
    NOPDF
    NOSEARCH
    NOSET
    NOSTATIC
    NOREFCHECK
    NOT_VALIDATE_TABLES
    NOVALID
    NOXML
    OPTIPNG
    OUTPUTNAME
    PAGEFILES
    PARAMS
    PROFARCH
    PROFAUDIENCE
    PROFCONDITION
    PROFCONFORMANCE
    PROFILE_URN
    PROFLANG
    PROFOS
    PROFOUTPUTFORMAT
    PROFREVISION
    PROFREVISIONFLAG
    PROFROLE
    PROFSECURITY
    PROFSTATUS
    PROFUSERLEVEL
    PROFVENDOR
    PROFWORDSIZE
    REMARKS
    REMARK_STR
    RESULTCHECK
    ROOTID
    SETDATE
    SHOW
    SRC_FORMAT
    STATIC_DIR
    STATIC_HTML
    STRINGPARAMS
    STYLEDEVEL
    STYLEROOT
    TARGET
    TXT_IGNORE_STYLEROOT
    TXT_PARAMS
    WH_SEARCH
    VALID_ROOTELEMENTS
    VALIDATE_IDS
    VALIDATE_IMAGES
    VERBOSITY
    XEP_CONFIG_FILE
    XEP_CMD_OPTIONS
    XEP_JAVA_FLAGS
    XEP_JAVA_JARS
    XEP_JAVA_OPTIONS
    XEP_WRAPPER
    XMLFORMAT_CONFIG_FILE
    XML_MAIN_CATALOG
    XML_USER_CATALOGS
    XSLTPARAM
    XSLTPROC
    XSLTPROCESSOR
)
# unset all for a fresh start, but preserve $DOCCONF - it might have been set
# by having sourced a DC-file

[[ -n "$DOCCONF" ]] && DOCCONF_SAVE=$DOCCONF
unset "${VARLIST[@]}"
[[ -n "$DOCCONF_SAVE" ]] && DOCCONF=$DOCCONF_SAVE


# The following UNSETLIST contains variables local to this script
# To be on the safe side, we also want to unset a few variables before we start
# because they are used/defined in make or may cause other harm if accidentally
# set
#
declare -a UNSETLIST
UNSETLIST=(
    ADOC_SET_CMDL
    BIN_DIR
    BUILD_DIR_CMDL
    COLOR_CMDL
    CONFIG
    DC_PATH_EXISTS
    DOC_DIR_CMDL
    DOCBOOK5_RNG_URI_CMDL
    DOCCONF_CMDL
    DOCCONF_NAME
    DAPSROOT_CMDL
    FALLBACK_STYLEROOT_CMDL
    HELP_SUBCMD
    MAIN_CMDL
    R_DIR
    STYLEROOT_CMDL
    VERBOSITY_CMDL
)
unset "${UNSETLIST[@]}"

# PATHLIST contains all variables holding a path. Relative paths need to be
# made absolute and we need this list in order to know which variables hold
# path information
#
# This list must not include FALLBACK_STYLEROOT, since we allow multiple
# values here.
# TODO: Check multiple FALLBACK_STYLEROOT paths
#
declare -A PATHLIST
PATHLIST=(
  [SPELL_EXTRA_DICT]="additional spell dictionary"
  [BUILD_DIR]="build directory"
  [DAPSROOT]="DAPS root directory"
  [DOCCONF]="DC-file"
  [DOCCONF_DEFAULT]="default DC-file"
  [EPUB_CSS]="CSS file for EPUB"
  [FOP_CONFIG_FILE]="FOP configuration file"
  [FOP_WRAPPER]="FOP wrapper script"
  [HTML_CSS]="CSS file for HTML"
  [JING_WRAPPER]="Jing wrapper script"
  [MAIN]="MAIN-file"
  [STATIC_DIR]="HTML resource directory"
  [STYLEDEVEL]="development directory for stylesheets"
  [STYLEROOT]="stylesheet directory"
  [XEP_CONFIG_FILE]="XEP configuration file"
  [XEP_WRAPPER]="XEP wrapper script"
  [XMLFORMAT_CONFIG_FILE]="xmlformat configuration file"
)

# ----------------------------------------------------------------------------
# We need to set some basic defaults outside of $DEFAULT_CONFIG

# this script's name
ME=$(basename "$0")

# default config file
DEFAULT_CONFIG="@sysconfdir@/daps/config"

# The default DAPSROOT
DAPSROOT_DEFAULT="@pkgdatadir@"

# default libdir
DEFAULT_LIB_DIR="${DAPSROOT_DEFAULT}/lib"
DEFAULT_LIBEXEC_DIR="${DAPSROOT_DEFAULT}/libexec"


# Config files
# ------------
# By default USER_CONFIG is parsed
# if DAPS_CONFIG_FILE is set (via --config on the command line),
# USER_CONFIG is ignored
# The file that is parsed in the end is stored in CONF_TO_PARSE
#
USER_CONFIG_OLD="$HOME/.daps/config"
USER_CONFIG="$HOME/.config/daps/dapsrc"
CONF_TO_PARSE=""

# if run from a terminal, set default verbosity to 1, otherwise (script, pipe)
# set it to 0

if [[ -t 1 ]]; then
    VERBOSITY=1
else
    VERBOSITY=0
fi

# Set the maximum number of concurrent jobs to the number of cores
# If grep -E does not return something useful, set it to "2" as a sane default
JOBS=$(grep -E -s -m1 "cpu cores\s*:" /proc/cpuinfo 2>/dev/null | sed 's/cpu cores\s*:\s*//')
[[ -z $JOBS ]] && JOBS=2

#---------------------------------------------------
# SUBCOMMANDS
#
# Associative Array
#  Key   = subcommand
#  Value = function call (from lib/daps_functions)
#
#
# The subcommands can be executed using:
#   ${SUBCOMMANDS[$SUBCMD]} $SUBCMD ${SCMD_ARGS[@]}
# Using such an array rather than a function to call the subcommands has
# the advantage that we can very easily check whether a subcommand is valid
# or not by just testing if ${SUBCOMMANDS[$SUBCMD]} is set

declare -A SUBCOMMANDS
declare -A HELP_SUBCOMMAND

SUBCOMMANDS[bigfile]="bigfile"
HELP_SUBCOMMAND[bigfile]="Creates a single XML file (bigfile) from the MAIN-file referenced in the\nDC-file or specified on the command line by following all xi:includes.\nIf a ROOTID is specified, all xref-links pointing to locations outside the\nscope defined by the ROOTID, are replaced by text-links."

SUBCOMMANDS[clean]="no_opts"
HELP_SUBCOMMAND[clean]="Removes all profiled XML sources and temporary files generated by DAPS."

SUBCOMMANDS[clean-all]="no_opts"
HELP_SUBCOMMAND[clean-all]="Removes all data (documents, images, logfiles, profiled XML, ...) generated\nby DAPS."

SUBCOMMANDS[clean-images]="no_opts"
HELP_SUBCOMMAND[clean-images]="Removes the results of all image conversions generated by DAPS."

SUBCOMMANDS[clean-package]="no_opts"
HELP_SUBCOMMAND[clean-package]="Removes all generated package data for a given DC- or MAIN-file.\nImage conversion results and profiled XML sources will not be deleted."

SUBCOMMANDS[clean-results]="no_opts"
HELP_SUBCOMMAND[clean-results]="Removes all generated documents and logfiles for a given DC- or MAIN-file.\nImage conversion results and profiled XML sources will not be deleted."

SUBCOMMANDS[dapsenv]="debugging"
HELP_SUBCOMMAND[dapsenv]="DEBUGGING: Shows a list of internal variables and their values."

SUBCOMMANDS[dist-webhelp]="build_generic"
HELP_SUBCOMMAND[dist-webhelp]="Creates a distributable tar archive of a webhelp document\n(including images and css)."

SUBCOMMANDS[dist-webhelp-name]="show_names"
HELP_SUBCOMMAND[dist-webhelp-name]="Print the file name that would result when building a distributable tar archive\nof a webhelp document."

SUBCOMMANDS[epub]="build_epub"
HELP_SUBCOMMAND[epub]="Build an eBook from the XML sources."

SUBCOMMANDS[epub-name]="show_names"
HELP_SUBCOMMAND[epub-name]="Print the file name that would result when building an eBook."

SUBCOMMANDS[getimages]="getimages"
HELP_SUBCOMMAND[getimages]="List and/or display images (in a viewer of your choice) referenced in an\nXML file or by rootid."

SUBCOMMANDS[html]="build_html"
HELP_SUBCOMMAND[html]="Build an HTML document from the XML sources."

SUBCOMMANDS[html-dir-name]="show_names"
HELP_SUBCOMMAND[html-dir-name]="Print the directory name that would result when building an HTML book."

SUBCOMMANDS[images]="build_images"
HELP_SUBCOMMAND[images]="Generate images for the given document."

SUBCOMMANDS[linkcheck]="linkcheck"
HELP_SUBCOMMAND[linkcheck]="Validates ftp and http(s) links in XML sources."

SUBCOMMANDS[list-file]="filelists"
HELP_SUBCOMMAND[list-file]="Lists the filename that contains the ID specified with --rootid."

SUBCOMMANDS[list-images-missing]="filelists"
HELP_SUBCOMMAND[list-images-missing]="Prints a list of images that are referenced in the XML sources but are missing\nin the images' source directory."

SUBCOMMANDS[list-images-multisrc]="filelists"
HELP_SUBCOMMAND[list-images-multisrc]="List images for which multiple sources exist."

SUBCOMMANDS[list-srcfiles]="filelists"
HELP_SUBCOMMAND[list-srcfiles]="List all source files used to build the document specified by\nthe DC-file (XML-files, images, entity declarations, DC-file).\nUse the --no* options to exclude certain types."

SUBCOMMANDS[list-srcfiles-unused]="filelists"
HELP_SUBCOMMAND[list-srcfiles-unused]="Print a list of all source XML files from the xml directory\n and images from images/src/ _not_ used in the document referenced by the DC- or MAIN-file."

SUBCOMMANDS[locdrop]="build_locdrop"
HELP_SUBCOMMAND[locdrop]="Create all tar archives required to distribute a complete set for translation.\nRequires DocBook 5 document with <info><dm:docmanager><dm:translation>yes</dm:translation></dm:docmanager></info> element."

SUBCOMMANDS[man]="build_man"
HELP_SUBCOMMAND[man]="Build one or more man pages from suitable XML sources. All <refentry> parts\nfrom the source file(s) will be transformed to man pages."

SUBCOMMANDS[man-dir-name]="show_names"
HELP_SUBCOMMAND[man-dir-name]="Print the directory name that would result when building man pages."

SUBCOMMANDS[mobi]="build_epub"
HELP_SUBCOMMAND[mobi]="Build an eBook for Amazon Kindle readers from the XML sources."

SUBCOMMANDS[mobi-name]="show_names"
HELP_SUBCOMMAND[mobi-name]="Print the file name that would result when building an Amazon Kindle book."

SUBCOMMANDS[nothing]="debugging"
HELP_SUBCOMMAND[nothing]="DEBUGGING: Benchmarking target."

SUBCOMMANDS[optipng]="build_generic"
HELP_SUBCOMMAND[optipng]="Reduce the size of the source PNG images using 'optipng'.\nNOTE: This command will directly alter your source images!"

SUBCOMMANDS[package-html]="package-html"
HELP_SUBCOMMAND[package-html]="Create all archives and files needed for packaging an\nHTML document (chunked HTML or single HTML)."

SUBCOMMANDS[package-html-dir-name]="show_names"
HELP_SUBCOMMAND[package-html-dir-name]="Print the directory name that would result when building\nan html package."

SUBCOMMANDS[package-pdf]="package-pdf"
HELP_SUBCOMMAND[package-pdf]="Create all archives and files needed for packaging a PDF document."

SUBCOMMANDS[package-pdf-dir-name]="show_names"
HELP_SUBCOMMAND[package-pdf-dir-name]="Print the directory name that would result when building\na pdf package."

SUBCOMMANDS[package-src]="package-src"
HELP_SUBCOMMAND[package-src]="creates a distributable source archive containg the profiled sources of the complete set\nincluding the original source images."

SUBCOMMANDS[package-src-name]="show_names"
HELP_SUBCOMMAND[package-src-name]="Print the file name that would result when building a distributable source\narchive."

SUBCOMMANDS[pdf]="build_pdfs"
HELP_SUBCOMMAND[pdf]="Build a PDF document from the XML sources."

SUBCOMMANDS[pdf-name]="show_names"
HELP_SUBCOMMAND[pdf-name]="Print the file name that would result when building a grayscale PDF document."

SUBCOMMANDS[productinfo]="build_generic"
HELP_SUBCOMMAND[productinfo]="Print the contents of the tags <productname> and <productnumber for the given ROOTID"

SUBCOMMANDS[profile]="build_generic"
HELP_SUBCOMMAND[profile]="Create profiled souces from the original XML sources. If the MAIN-file does\nnot contain profiling instructions, link the files into the profile directory."

SUBCOMMANDS[real-clean]="no_opts"
HELP_SUBCOMMAND[real-clean]="Removes all data (documents, images, logfiles, profiled XML, ...) generated\nby DAPS"

SUBCOMMANDS[showenv]="showenv"
HELP_SUBCOMMAND[showenv]="DEBUGGING: Target reserved for daps-docmanager"

SUBCOMMANDS[showvariable]="debugging"
HELP_SUBCOMMAND[showvariable]="DEBUGGING: Show the value of a given variable.\nUsage: showvariable VARIABLE=<VARNAME>"

SUBCOMMANDS[spellcheck]="spellcheck"
HELP_SUBCOMMAND[spellcheck]="Spellchecks the file specified with --file or the document specified by rootid."

SUBCOMMANDS[stylecheck]="stylecheck"
HELP_SUBCOMMAND[stylecheck]="Performs a style check on the given DC-file or rootid."

SUBCOMMANDS[text]="build_text"
HELP_SUBCOMMAND[text]="Build an ASCII text document the from the XML sources. Text output is\ngenerated by creating a single file HTML page parsing the result with w3m."

SUBCOMMANDS[text-name]="show_names"
HELP_SUBCOMMAND[text-name]="Print the file name that would result when building an ASCII text document."

SUBCOMMANDS[unpack-locdrop]="unpack-locdrop"
HELP_SUBCOMMAND[unpack-locdrop]="Unpack a localization drop packages source."

SUBCOMMANDS[validate]="validate"
HELP_SUBCOMMAND[validate]="Validate the profiled XML sources referenced by the DC- or MAIN-file."

SUBCOMMANDS[webhelp]="webhelp"
HELP_SUBCOMMAND[webhelp]="Build an HTML document with a table of contents/search frame (aka webhelp)\nfrom the XML sources."

SUBCOMMANDS[webhelp-dir-name]="show_names"
HELP_SUBCOMMAND[webhelp-dir-name]="Print the directory name that would result when building a webhelp document."

SUBCOMMANDS[xmlformat]="xmlformat"
HELP_SUBCOMMAND[xmlformat]="Prettify XML sources using the xmlformat program.\n The default configuration files are included with DAPS (/etc/daps/docbook-xmlformat-*.conf)."

# ----------------------------------------------------------------------------
# FUNCTIONS
#
# We need to declare a few basic functions first because they are needed
# immediately. All other functions can be found at
# $DAPSROOT/lib/daps-functions
# ---------
# Help
#

function daps_help {
    cat <<EOF_helptext
Usage:
  1. $ME -d DC-file [--options] <subcommand> [--subcommand-options]
  2. $ME -m MAIN file [--options] <subcommand> [--subcommand-options]


Global Options:
  --adocattr="NAME=VALUE"   Overwrite, define or delete an AsciiDoc document
                            attribute. To overwrite an attribute already
                            defined in the AsciiDoc document, use NAME=VALUE,
                            or just NAME for attributes without a value. To delete
                            a value set in the document use NAME!. To set
                            a value that is not already set in the document, use
                            NAME=VALUE@.
                            Default: unset
                            This option can be specified multiple times. Only
                            works with AsciiDoc sources and is ignored otherwise.
  --adocimgdir=IMG_DIR      Specify a directory for the images used in the
                            AsciiDoc sources. Must contain all images,
                            subdirectories are ignored.
                            Not required if the images reside in the directory
                            structure required by for DocBook projects
                            (see DAPS manual).
                            Default: unset
                            Only works with AsciiDoc sources and is ignored
                            otherwise.
  --adocset                 If specified, DAPS tries to convert the AsciiDoc
                            document into a set. Requires an AsciiDoc document
                            that consists of parts (each part will be
                            converted into a book in a set),
                            Default: unset
  --builddir=BUILD_DIR      Directory where every output $ME generates will
                            end up.
                            Default: <doc dir>/build/
  --color=(0|1)             By default errors, results, warnings and certain
                            info messages are printed in color using bash color
                            codes. Set to '0' to turn off colors.
                            Default: 1 (when the output does not go to a
                                        terminal, colored output will be
                                        disabled automatically)
  --config=CFG-FILE         Set a configuration file for DAPS that overwrites
                            defaults set in /etc/daps/config.
                            By default (when this option is not set)
                            ~/.config/daps/dapsrc will be parsed, if existing.
                            In case --config is set, ~/.config/daps/dapsrc
                            will be ignored.
                            Default: ~/.config/daps/dapsrc
  --commands                Show a list of available DAPS sub commands
  --debug                   Print debugging messages. Alternatively see the
                            verbosity options for an output that is better
                            readable.
  --docconfig=DC-file,
  -d DC-file                Path to doc config file to use. Mandatory,
                            unless there is only a single DC-file in the
                            current directory or unless you have configured a
                            default value (DOCCONF_DEFAULT) in \$USER_CONFIG.
                            Note: Options --docconfig and --main exclude
                                  each other.
  --fb_styleroot=DIR        Fallback styleroot directories. Can only be used in
                            conjunction with --styleroot. By default, the
                            DocBook stylesheets are used as a fallback if
                            custom styles for an output format are not present.
                            With this option you can specify a list of
                            alternative fallbacks (space separated absolute
                            paths). The directories will be tested in the order
                            specified, the first one that applies to the
                            requested format, will be used. The original
                            DocBook stylesheets will be used as a last resort.
                            Useful if you have forks of your custom
                            stylesheets.
  --force                   Force a rebuild of the document even when an
                            up-to-date version exists.
  --help, -h                Help
  --jobs=X                  Specify how many parallel jobs to use. Higher
                            numbers will significantly increase the processing
                            speed, but will also set your machine under heavy
                            load, up to a point where it may become
                            (temporarily) unresponsive.
                            Default: Use as man jobs as available CPU cores.
  --main=MAINFILE
  -m MAINFILE               Path to the main file defining your document.
                            Note: Options --main and --docconfig exclude
                                  each other.
  --schema=URN              URN to a DocBook 5 schema that is to be used for
                            validation. Will be ignored when validating
                            DocBook 4 documents.
                            Note: To validate with a local schema, specify an
                                  absolute path with a "file://" prefix
                                  (e.g. "file:///foo/schema.rnc").
  --styleroot=DIR           By default, daps uses the DocBook stylesheets to
                            create output. If you have your own set of
                            stylesheets, specify the absolute path to the
                            stylesheet directory here. The DocBook stylesheets
                            will be used as a fallback in case styles are not
                            defined for all output formats.
  --verbosity=0, -v0        Verbosity Level 0 (print 1 line of results)
  --verbosity=1, -v1, -v    Verbosity Level 1 (print intermediate results)
  --verbosity=2, -v2, -vv   Verbosity Level 2 (print all files created)
  --verbosity=3, -v3, -vvv  Verbosity Level 3 (print all commands, very
                            verbose)
  --version                 Print version number
  --xsltprocessor=PROCESSOR Specify an XSLT processor that is used to transform
                            the XML files. Currently supported are "xsltproc"
                            and "saxon" (version 6).
                            Default: xsltproc

Subcommands:
   help                       Print this help.

  Generate Books:
    epub                      ePUB book
    html                      HTML book (chunked or single file HTML)
    man                       man pages
    mobi                      Amazon Kindle eBook
    pdf                       PDF book (color, grayscale, printable)
    text                      ASCII book
    webhelp                   HTML book with collapsible TOC and search


  File lists:
    list-file                 Lists the filename that contains the ID specified
                              with the mandatory parameter --rootid.
    list-srcfiles             List source files (XML sources, images, entity
                              declarations, DC-file) used by the document
                              reference by the DC-file.
    list-srcfiles-unused      List files from the document and image source and
                              directories not used by the document reference
                              by the DC-file.
    list-images-missing       List images referenced in the XML sources but
                              missing in the images' source directory.
    list-images-multisrc      List images for which multiple sources exist
                              (e.g. foo.svg and foo.png).

  Cleaning up:
    clean                     Remove all profiled sources and temporary files.
    clean-images              Remove all generated images.
    clean-package             Remove all generated package data for the given
                              DC-file. Generated images and profiled sources
                              will _not_ be deleted.
    clean-results             Remove all generated books, archives, and log
                              files for the given DC-file. Generated images
                              and profiled sources will _not_ be deleted.
    clean-all, real-clean     Remove everything generated by $ME.

  Packaging:
    package-html              Provide an HTML tarball (chunked HTML or
                              single HTML), desktop, document,
                              and/or page files (for KDE and GNOME).
    package-pdf               Provide a PDF, desktop, document, and/or
                              page files (for KDE and GNOME).
    package-src               Provide profiled XML sources and graphics

  Deploying:
    locdrop                   Provide everything that is needed to translate a
                              set.
    unpack-locdrop            Unpack a localization drop packages source.

  Other Commands:
    getimages                 List or display images from a profiled DocBook
                              XML file.
    linkcheck                 Link checker for links from <ulink> tags
    optipng                   Optimize file size of source PNGs.
    profile                   Profile XML sources.
    spellcheck                Spellchecks the file specified with --file or the
                              document specified by rootid.
    stylecheck                Performs a style check on the given DC-file or
                              rootid.
    validate                  Validate profiled sources. Automatically profiles
                              the XML sources if needed.
    xmlformat                 Prettify the XML source files using
                              daps-xmlformat.

  File and Directory Names:
    <target>-name             Print resulting file name for <target>. <target>
                              may be one of color-pdf, epub, html-single,
                              pdf, txt.
    <target>-dir-name         Print resulting directory name for <target>.
                              <target> may be html, man or webhelp.

  Debugging:
    bigfile                   Creates a single "big" XML file by resolving
                              xi:includes. Useful for detecting validation
                              errors that cannot be found otherwise.
    dapsenv                   Print a list of the most important make variables
                              and their value.
    images                    Generates all images for the given DC-file or
                              rootid.
    showvariable              Print value of a given make variable:
                              $ME showvariable VARIABLE=<MAKE_VARIABLE>.

Type '$ME <subcommand> -h' for help on a specific subcommand.
EOF_helptext
}

function daps_commands {
    # show a list of available subcommands from the SUBCOMMANDS array
    # ignore the commands set to deprecated
    local KEY

    for KEY in "${!SUBCOMMANDS[@]}"; do
        #if [[ deprecated == "${SUBCOMMANDS[$KEY]}" ]]; then
        #    continue
        #else
        #    echo "$KEY"
        #fi
        echo "$KEY"
    done | sort -u
}

# ---------
# Clean up
#
function clean_daps {
    [[ -f $SETFILES_TMP ]] && rm -f "$SETFILES_TMP"
}

# ---------
# Verbose error handling
#
function exit_on_error {
    echo -e "ERROR: ${1}" >&2
    clean_daps
    exit 1;
}

# ---------
# Get absolute path, remove trailing / and test if path is valid
#
function sanitize_path {
    # Takes values
    # $1 = path
    # $2 = variable name holding $1
    # $3 = additional base dir for $1 (optional)
    #
    # sets absolute path without trailing / for $1, links are being followed
    # also tests if paths are valid
    #
    # in case of a non-existing path, returns 2 if variable name matches
    # _WRAPPER, else returns 1
    #
    local ABSPATH BASEDIR MYPATH ORIGIN_TEXT VARNAME VN WRONGPATH

    MYPATH=$1
    VARNAME=$2
    [[ -n "$3" ]] && BASEDIR=$3

    WRONGPATH=0

        # Do nothing if $1 is an empty value
    [[ -z "$MYPATH" ]] && return

    # Remove preceding file:// scheme
    if [[ ${MYPATH:0:5} = file: ]]; then
        MYPATH=${MYPATH#file:}
    fi

    # ignore values that need to be set by configure
    # (makes it possible to directly use a Git clone)
    [[ $MYPATH =~ @[a-zA-Z]*@ ]] && return

    # 1. Remove trailing Slash
    #
    MYPATH=${MYPATH%/} # remove trailing slash

    if [[ $MYPATH =~ ^~.* ]]; then
        # 2. Replace ~/ with $HOME
        if [[ $MYPATH =~ ^~/.* ]]; then
            MYPATH=${MYPATH/#\~\//$HOME/}
        else
            # 3. Replace ~USER with a real path
            # the %q option to printf quotes and escapes dangerous characters
            # see http://stackoverflow.com/questions/2069467/have-to-determine-all-users-home-directories-tilde-scripting-problem
            eval MYPATH="$(printf "%q" "$MYPATH")"
        fi
    fi

    if [[ "/" != ${MYPATH:0:1} ]]; then
        [[ -n "$BASEDIR" ]] && MYPATH="${BASEDIR}/${MYPATH}"
        ABSPATH=$(readlink -en "$MYPATH")
        if [[ 0 -eq $? ]]; then
            declare -g $VARNAME="$ABSPATH"
        else
            WRONGPATH=1
        fi
    else
        # path is already absolute, set to MYPATH (because of having cut
        # the trailing /
        if [[ -d $MYPATH || -f $MYPATH ]]; then
            declare -g $VARNAME="$MYPATH"
        else
            WRONGPATH=1
        fi
    fi

    # in case of a wrong path
    if [[ 1 -eq $WRONGPATH ]]; then
        # remove _CMDL from variable name if exists
        # MAIN_CMDL => MAIN
        if [[ $VARNAME =~ _CMDL ]]; then
            VN="${VARNAME%_CMDL}"
            ORIGIN_TEXT="(provided on the command line: $MYPATH)"
        else
            VN="${VARNAME}"
            ORIGIN_TEXT="(provided via config file: $VARNAME=$MYPATH)"
        fi
        # if an entry in PATHLIST exists, use the variable name
        # description provided in the associative array
        # to get a better error message
        if [ ${PATHLIST[$VN]+_} ]; then
            exit_on_error "Wrong path for the ${PATHLIST[$VN]}\n       ${ORIGIN_TEXT}"
        else
            exit_on_error "$VARNAME=$MYPATH: Path does not exist"
        fi
    fi
}

# ----------------------
# Check all paths in $PATHLIST with sanitize_path
#
function check_pathlist {
    local _PATH BASEDIR VNAME
    BASEDIR=$1
    for VNAME in "${!PATHLIST[@]}"; do
        _PATH="${!VNAME}"
        if [[ -n "$_PATH" ]]; then
            sanitize_path "$_PATH" "$VNAME" "$BASEDIR"
        fi
    done
}

# ---------
# Try to automatically get the DOCCONF
#
function autoset_docconf {
    # if there is only one DOCCONF file in the current directory, use it
    # and also set DOC_DIR
    #
    local DC_FILENAME DC_PARENT DC_REAL_PATH DC_REAL_DIR
    declare -a DC_COUNT
    DC_COUNT=( $(find -L . -maxdepth 1 -name "${CONF_PREFIX}*" -type f) )
    if [[ 1 -eq ${#DC_COUNT[@]} ]]; then
        # There is only one DOCCONF file
        #
        # two possibilities:
        # 1. We are already in DOC_DIR
        # 2. We are in the documents build result directory
        # (DOC_DIR/build/<name>), where daps creates a link to the
        # real ENV file
        if [[ -h ${DC_COUNT[0]} ]]; then
            # DOCCONF is a link
            DC_REAL_PATH=$(readlink -nm "${DC_COUNT[0]}")
            if [[ 0 -eq $? ]]; then
            declare -g $VARNAME="$ABSPATH"
        else
            exit_on_error "$VARNAME=$MYPATH: Path does not exist"
        fi
            DC_REAL_DIR=$(dirname "$DC_REAL_PATH")
            DC_FILENAME=$(basename "$DC_REAL_PATH")
            DC_PARENT=${DC_FILENAME#${CONF_PREFIX}*}
            if [[ -e ${DC_REAL_DIR}/build/${DC_PARENT}/$DC_FILENAME ]]; then
                # we are in the result dir - set DOCCONF to the
                # real path (with links "resolved")
                DOCCONF_CMDL="$DC_REAL_PATH"
            else
                # we are in DOC_DIR
                # preserve links
                DOCCONF_CMDL="${PWD}/${DC_COUNT[0]}"
            fi
        else
            # no link, we are in DOC_DIR
            sanitize_path "${DC_COUNT[0]}" "DOCCONF_CMDL"
        fi
        # set DOC_DIR
        DOC_DIR=$(dirname "$DOCCONF_CMDL")
        if [[ 2 -le $VERBOSITY ]]; then
            echo "Using automatically detected DOCCONF $DOCCONF_CMDL"
        fi
    else
        # more than one or no DOCCONF
        exit_on_error "Could not find a valid MAIN file.\nPlease specify either a DOCCONF or a MAIN file at the command line"
    fi
}


# ---------
# Recover command-line values
#
function recover_cmdl_values {
    # adoc attributes is special because it can be specified multiple times
    # we want to keep all values
    test -n "$ADOC_ATTRIBUTES_CMDL" && ADOC_ATTRIBUTES="$ADOC_ATTRIBUTES $ADOC_ATTRIBUTES_CMDL"
    test -n "$ADOC_SET_CMDL"  && ADOC_SET="$ADOC_SET_CMDL"
    test -n "$BUILD_DIR_CMDL" && BUILD_DIR="$BUILD_DIR_CMDL"
    test -n "$COLOR_CMDL"     && COLOR="$COLOR_CMDL"
    test -n "$DOCBOOK5_RNG_URI_CMDL" && DOCBOOK5_RNG_URI="$DOCBOOK5_RNG_URI_CMDL"
    test -n "$DOCCONF_CMDL"   && DOCCONF="$DOCCONF_CMDL"
    test -n "$DAPSROOT_CMDL"  && DAPSROOT="$DAPSROOT_CMDL"
    test -n "$FALLBACK_STYLEROOT_CMDL" && FALLBACK_STYLEROOT="$FALLBACK_STYLEROOT_CMDL"
    test -n "$MAIN_CMDL"      && MAIN="$MAIN_CMDL"
    test -n "$STYLEROOT_CMDL" && STYLEROOT="$STYLEROOT_CMDL"
    test -n "$VERBOSITY_CMDL" && VERBOSITY="$VERBOSITY_CMDL"
    test -n "$XSLTPROCESSOR_CMDL" && XSLTPROCESSOR="$XSLTPROCESSOR_CMDL"
}

# ---------
# Config file parser for DC-files and general configs
# More secure than just sourcing the config files
#

function parse_config {

    # Inspired by
    # https://stackoverflow.com/questions/16571739/bash-parsing-variables-from-config-file
    # Takes the config file to parse as required value
    #
    [[ -z $1 ]] && exit_on_error "Function parse_config must be called with a config file as an argument"

    local CFG CONCAT KEY LINE_NO OLD_IFS VALUE

    CFG=$1
    LINE_NO=0
    OLD_IFS="$IFS"
    shopt -s extglob
    while IFS='= ' read KEY VALUE; do
        # no cocatenation by default
        CONCAT=0
        let LINE_NO++
        # skip empty lines
        [[ -z "$KEY" ]] && continue
        # skip comments
        [[ "$KEY" =~ ^[[:space:]]*# ]] && continue
        # skip export statements (were allowed in DAPS <= 2.2.0)
        [[ "$KEY" =~ ^[[:space:]]*export$ ]] && continue

        # Possible KEY/VALUE pairs
        # KEY01 = VALUE
        # KEY02=VALUE
        # KEY03 = "VALUE"
        # KEY04="VALUE"
        # KEY05 = VALUE   # comment
        # KEY06=VALUE     # comment
        # KEY07 = "VALUE" # comment
        # KEY08="VALUE"   # comment
        # KEY09 += VALUE
        # KEY10+=VALUE
        # KEY11 += "VALUE"
        # KEY12+="VALUE"
        # KEY13 += VALUE   # comment
        # KEY14+=VALUE     # comment
        # KEY15 += "VALUE" # comment
        # KEY16+="VALUE"   # comment
        # KEY17+="'VALUE17'"
        # KEY18+=""VAL\\\"UE18""
        # KEY19="  VALUE 19  "
        # KEY20="  VAL \\\#UE 20  "# # #  comment # ##
        # KEY21==VALUE
        # KEY22 == "VALUE"

        # not supported
        # KEY = "Val #ue"        use "Val \\\#ue" instead
        # KEY = "Val \#ue"       use "Val \\\#ue" instead
        # KEY = "c:\windows\foo" use "c:\\\windows\\\foo" instead

        # removing opening/closing single/double quotes from VALUE
        # ${string/#substring/replacement}
        # ${string%%substring}
        #
        VALUE="${VALUE%% \#*}"        # del inline right comments
        VALUE="${VALUE/#=/}"          # del leading "=" (allows k==v)
        VALUE="${VALUE%%*( )}"        # del trailing spaces
        VALUE="${VALUE/#[\"\'\`\´]/}" # del opening quotes and ticks
        VALUE="${VALUE/%[\"\'\`\´]/}" # del closing quotes and ticks

        # KEY += VALUE
        if [[ "$VALUE" =~ ^\+= ]]; then
            CONCAT=1
            VALUE="${VALUE#+=*}"      # del "+="
            VALUE="${VALUE##*( )}"    # del leading spaces
            VALUE="${VALUE/#[\"\'\`\´]/}" # del closing quotes and ticks
        # KEY+=VALUE
        elif [[ "$KEY" =~ \+$ ]]; then
            CONCAT=1
            KEY="${KEY%*+}"           # del trailing "+"
        fi

        # check if KEY is a valid variable name
        [[ "$KEY" =~ ^[_[:alpha:]][_[:alnum:]]*$ ]] || exit_on_error "Invalid key value \"$KEY\" in config-file $CFG:$LINE_NO"

        # set variables
        if [[ 1 -eq $CONCAT ]]; then
            declare -g $KEY="${!KEY} $VALUE"
        else
            declare -g $KEY="$VALUE"
        fi

        # Warn on empty values
        if [[ "$VALUE" = "\"\"" || "$VALUE" = "''" ]]; then
            ccecho "warn" "Warning: Quotes-only value for \"$KEY\" in config-file $CFG:$LINE_NO"
        fi
    done < <(grep "" "$CFG")
    # above: see https://stackoverflow.com/questions/4165135/how-to-use-while-read-bash-to-read-the-last-line-in-a-file-if-there-s-no-new
    shopt -u extglob
    IFS="$OLD_IFS"
}



trap "exit_on_error '\nCaught SIGTERM/SIGINT'" SIGTERM SIGINT
trap "clean_daps" ERR EXIT

# ----------------------------------------------------------------------------
# Parsing the command line arguments with GNU getopt
#
# In order to separate general daps parameters from subcommand parameters,
# we are setting POSIXLY_CORRECT before parsing the first time.
# This causes getopt to interpret all remaining parameters as non-option
# parameters as soon as the first non-option parameter (the subcommand) is
# found. This value must be _exported_

export POSIXLY_CORRECT=1

# So, the first getopt go will parse all parameters listed directly after the
# daps command, leaving an array ($@) with the subcommand and it's
# parameters, which can be parsed in a second getopt go.

#-------------------------------
# Parsing the daps parameters
#
# If variables such as $BUILD_DIR, $DOCCONF, and $DAPSROOT are set via command
# line switch, we do not want to overwrite them by any other file we source
# at a later stage (command line always wins).
# Declaring the variables as read-only is unfortunately not an option, since
# every attempt to (un)set a read-only variable throws an error - something
# we do not want when sourcing a config file.
# Therefore we need to save each variable twice in order to recover the
# original value.

ARGS=$(getopt -o d:e:hm:v:: -l adocattr:,adocimgdir:,adocset,builddir:,config:,color:,colour:,commands,debug,docconfig:,dapsroot:,envfile:,fb_styleroot:,force,help,jobs:,main:,schema:,styleroot:,verbosity::,version,xsltprocessor: -n "$ME" -- "$@")

# Exit when getopt returns errors
#
GETOPT_RETURN_CODE=$?
[[ 0 -ne $GETOPT_RETURN_CODE ]] && exit $GETOPT_RETURN_CODE

eval set -- "$ARGS"

while true ; do
    case "$1" in
        --adocattr)
            ADOC_ATTRIBUTES_CMDL="$ADOC_ATTRIBUTES_CMDL --attribute=\"$2\""
            shift 2
            ;;
        --adocimgdir)
            [[ -d $2 ]] || exit_on_error "ADOC_IMG_DIR \"$2\" is not a valid directory"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "ADOC_IMG_DIR_CMDL"
            ADOC_IMG_DIR="$ADOC_IMG_DIR_CMDL"
            shift 2
            ;;
        --adocset)
            ADOC_SET_CMDL="yes"
            ADOC_SET="$ADOC_SET_CMDL"
            shift
            ;;
        --builddir)
            [[ -d $2 ]] || exit_on_error "BUILD_DIR \"$2\" is not a valid directory"
            [[ -w $2 ]] || exit_on_error "BUILD_DIR \"$2\" is not writable"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "BUILD_DIR_CMDL"
            BUILD_DIR="$BUILD_DIR_CMDL"
            shift 2
            ;;
        --config)
            [[ -s $2 ]] || exit_on_error "DAPS_CONFIG_FILE \"$2\" is not a valid file"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "DAPS_CONFIG_FILE"
            shift 2
            ;;
        --color|--colour)
            if [[ 1 -ne $2 && 0 -ne $2 ]]; then
                exit_on_error "Wrong value ($2) for COLOR. Must be \"0\" or \"1\""
            fi
            COLOR_CMDL=$2
            export COLOR="$COLOR_CMDL"
            shift 2
            ;;
        --commands)
            daps_commands
            exit 0
            ;;
        -d|--docconfig|-e|--envfile)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "DOCCONF_CMDL"
            DOCCONF="$DOCCONF_CMDL"
            shift 2
            ;;
        --dapsroot)
            [[ -d $2 ]] || exit_on_error "DAPSROOT \"$2\" is not a valid directory"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "DAPSROOT_CMDL"
            DAPSROOT="$DAPSROOT_CMDL"
#           DEVEL=1
            shift 2
            ;;
        --debug)
            # debug also implies VERBOSITY=2
            DEBUG=1
            VERBOSITY_CMDL=2
            VERBOSITY=$VERBOSITY_CMDL
            # enable JAVA debug messages (fop, xep)
            export VERBOSE=1
            shift
            ;;
        --fb_styleroot)
            # We are allowing multiple values, space-seperated
            for FBS in $2; do
                # make path absolute and strip trailing slash
                sanitize_path "$FBS" "FBS_LIST"
                FALLBACK_STYLEROOT_CMDL="$FALLBACK_STYLEROOT_CMDL $FBS_LIST"
            done
            FALLBACK_STYLEROOT="$FALLBACK_STYLEROOT_CMDL"
            shift 2
            ;;
        --force)
            FORCE_REBUILD=1
            shift
            ;;
        -h|--help)
            # if it's just "-h/--help", then print the global daps help
            # if "-h/--help" is followed by a subcommand, then set a marker
            # to call the subcommand's help
            shift;
            if [[ "" = "$2" ]]; then
                daps_help
                exit 0;
            else
                CALL_SCMDHELP=1
            fi
            ;;
        --jobs)
            if [[ $2 =~ ^[0-9][0-9]*$ ]]; then
                JOBS="$2"
            else
                exit_on_error "Wrong value ($2) for --jobs. Must be a numeric"
            fi
            shift 2
            ;;
        -m|--main)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "MAIN_CMDL"
            MAIN="$MAIN_CMDL"
            shift 2
            ;;
        --schema)
            DOCBOOK5_RNG_URI_CMDL="$2"
            DOCBOOK5_RNG_URI="$DOCBOOK5_RNG_URI_CMDL"
            shift 2
            ;;
        --styleroot)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "STYLEROOT_CMDL"
            STYLEROOT="$STYLEROOT_CMDL"
            shift 2
            ;;
        -v|--verbosity)
            # $VERBOSITY will be parsed in the makefiles
            # VERBOSITY=0: print only final results message (default)
            # VERBOSITY=1: results of each target that is called
            # VERBOSITY=2: detailed output of each target
            #
            if [[ 1 -eq $DEBUG ]]; then
                VERBOSITY_CMDL=2
            else
                if [[ 0 = "$2" ]]; then
                    VERBOSITY_CMDL=0
                elif [[ 1 = "$2" || "" = "$2" ]]; then
                    VERBOSITY_CMDL=1
                elif [[ 2 = "$2" || "v" = "$2" ]]; then
                    VERBOSITY_CMDL=2
                else
                    VERBOSITY_CMDL=3
                fi
            fi
            VERBOSITY="$VERBOSITY_CMDL"
            shift 2
            ;;
        --version)
            echo "$ME $VERSION"
            exit 0
            ;;
        --xsltprocessor)
            which "$2" >/dev/null 2>&1 || exit_on_error "Cannot find the XSLT processor \"$2\"."
            XSLTPROCESSOR_CMDL="$2"
            XSLTPROCESSOR="$XSLTPROCESSOR_CMDL"
            shift 2
            ;;
        --) shift ; break ;;
        *) exit_on_error "Internal error!" ;;
    esac
done

# You can only specify DOCCONF or MAIN, not both
#
if [[ -n "$DOCCONF_CMDL" && -n "$MAIN_CMDL" ]]; then
    exit_on_error "The options -d/--docconfig and --main exclude each other."
fi

# Check FALLBACK_STYLEROOT and STYLEROOT
#
if [[ -n "$FALLBACK_STYLEROOT" && -z "$STYLEROOT" ]]; then
    if [[ 0 -ne $VERBOSITY ]]; then
        echo "Warning: --styleroot is not specified, ignoring --fb_styleroot" >&2
    fi
fi

unset POSIXLY_CORRECT # we want the regular getopts behaviour on the second run

#-----------------------------------
# Store the subcommand and it's args

# extract the subcommand from $@ if $ME has been called with no arguments
# or with "help" as the only argument, run global help. If it was called with
# SUBCOMMAND help or help SUBCOMMAND, rewrite the command so the subcommand help
# is displayed.

if [[ -z "$1" ]] || [[ help = "$1" && -z "$2" ]]; then
    # Call: "$ME" or "$ME help"
    #
    daps_help
    exit 0
elif [[ help = "$2" ]]; then
    # Call: "$ME foo help ..."
    # Rewrite to "$ME foo -h"
    #
    SUBCMD=$1
    declare -a SCMD_ARGS=( "-h" )
elif [[ help = "$1" && -n "$2" ]]; then
    # Call: "$ME help foo"
    # Rewrite to "$ME foo -h"
    #
    SUBCMD=$2
    declare -a SCMD_ARGS=( "-h" )
elif [[ 1 -eq $CALL_SCMDHELP ]]; then
    SUBCMD=$1
    declare -a SCMD_ARGS=( "-h" )
else
    # No help
    #
    # Compatibility; checklink has been replaced ny linkcheck in DAPS 3.1
    if [[ checklink = $1 ]]; then
        SUBCMD="linkcheck"
        echo "Warning: Subcommand 'checklink' is deprecated, use 'linkcheck' instead." >&2
    else
        SUBCMD=$1
    fi
    shift
    declare -a SCMD_ARGS=( "$@" )

fi

# Now that we have the subcommand, check whether it is valid
#
if [[ -z ${SUBCOMMANDS[$SUBCMD]} ]]; then
    exit_on_error "Unknown subcommand \"$SUBCMD\"\nType '$ME help' to get a list of global parameters and subcommands"
fi

# Now check, whether subcommand help has been requested by -h or --help
# anywhere in the argument string or if SCMD_ARGS contains bad strings
#
case "${SCMD_ARGS[@]}" in
    "-h"|"-h "*|*" -h "*|*" -h"|"--help"|"--help "*|*" --help "*|*" --help")
        declare -a SCMD_ARGS=( "-h" )
        ;;
    *DOCCONF*|*DAPSROOT*|*DOC_DIR*|*MAIN*)
        if [[ showvariable != $SUBCMD ]]; then
            exit_on_error "Please specify DOC_DIR, DOCCONF, MAIN, or DAPSROOT via command line options"
        fi
esac


# ----------------------------------------------------------------------------
# Setting up the environment for the complete mechanics
#
# The environment is set up using the following hierarchy
# (1 == always wins)
#
# 1. Command line
#    - either as a real option
#    - or as variable declaration (FOO=bar) --> debugging and developing
# 2. DC-file
# 3. $USER_CONFIG (user config file)
# 4. @sysconfig@/daps/config or $DAPSROOT/etc/config
#
# In order to make developing easier, there is a hidden feature to set
# DAPSROOT, allowing to have multiple daps versions installed into
# different directories. You can switch between them by setting DAPSROOT
# accordingly. Either by command line switch --dapsroot or in  your user
# config file (DAPSROOT="<path>")
#
# Since command line values take precedence we need to recover them every
# time we source a file
#

# Set the config file that will get parsed:
#
if [[ -n $DAPS_CONFIG_FILE ]]; then
    CONF_TO_PARSE="$DAPS_CONFIG_FILE"
elif [[ -f $USER_CONFIG ]]; then
    CONF_TO_PARSE="$USER_CONFIG"
fi

#
# source the user config for the first time to get DAPSROOT
#

# Removing the Code to move an old user config and replace it with an error
if [[ -f $USER_CONFIG_OLD && ! -f $USER_CONFIG ]]; then
        exit_on_error "The DAPS user configuration file has moved from\n~/.daps/config to ~/.config/daps/dapsrc\nPlease move or delete $USER_CONFIG_OLD"
fi

# Set DAPSROOT via user config file
if [[ -s $CONF_TO_PARSE && -z "$DAPSROOT_CMDL" ]]; then
    parse_config "$CONF_TO_PARSE"
    # make DAPSROOT path absolute and remove trailing /
    [[ -n "$DAPSROOT" ]] && sanitize_path "$DAPSROOT" "DAPSROOT"
    recover_cmdl_values
fi

# IF we have a custom DAPSROOT, $DAPSROOT is set by now - if not, use the default
if [[ -n "$DAPSROOT" ]]; then
    # custom DAPSROOT was set
    if [[ ! -d "$DAPSROOT" ]]; then
        exit_on_error exit_on_error "DAPSROOT \"$2\" is not a valid directory"
    else
        # valid directory
        #  strip trailing slash
        DAPSROOT=${DAPSROOT%/}
        BIN_DIR="${DAPSROOT}/bin"
        export PATH=$BIN_DIR:$PATH
        LIB_DIR="${DAPSROOT}/lib"
        LIBEXEC_DIR="${DAPSROOT}/libexec"
        CONFIG="${DAPSROOT}/etc/config"
        XML_DEVEL_CATALOG="$XML_DEVEL_CATALOG $DAPSROOT/etc/catalog.xml"
    fi
else
    # default DAPSROOT
    # no need to set BIN_DIR here, since it should be in the default path
    #
    # if DAPSROOT_DEFAULT contains @...@ we are operating from a Git
    # checkout and no  --dapsroot was set
    #
    [[ $DAPSROOT_DEFAULT =~ @[a-zA-Z]*@ ]] && exit_on_error "You need to specify a DAPSROOT when using a Git checkout"
    DAPSROOT="$DAPSROOT_DEFAULT"
    LIB_DIR="$DEFAULT_LIB_DIR"
    LIBEXEC_DIR="$DEFAULT_LIBEXEC_DIR"
    CONFIG="$DEFAULT_CONFIG"
fi

# Path to the xslt processor wrapper script
#
XSLTPROC=${LIBEXEC_DIR}/daps-xslt


# ---------------------------------------------
# Source functions and parse system config
#
# Now that everything is in place, source the functions, parse the system
# config and the user config (again)
source "$LIB_DIR/daps_functions"
parse_config "$CONFIG"

# Parse user config
#
if [[ -s $CONF_TO_PARSE ]]; then
    parse_config "$CONF_TO_PARSE"
    # make DAPSROOT path absolute and remove trailing / (again)
    [[ -n "$DAPSROOT" ]] && sanitize_path "$DAPSROOT" "DAPSROOT"
fi
recover_cmdl_values

#----------------------------------
# Run early commands that do not need to have an environment fully set up

#
# run help if requested
#
if [[ "${SCMD_ARGS[@]}" = "-h" ]]; then
    # source additional functions
    #
    [[ -f $LIB_DIR/$SUBCMD ]] && source "$LIB_DIR/$SUBCMD"
    ${SUBCOMMANDS[$SUBCMD]} "$SUBCMD" "${SCMD_ARGS[@]}"
    exit 0
fi

# Sample call for early commands
#
#case "$SUBCMD" in
#    foo)
#      ${SUBCOMMANDS[$SUBCMD]} "${SCMD_ARGS[@]}"
#      exit
#      ;;
#esac

#-------------------------------------
# Parse DOCCONF and set up MAIN, DOC_DIR
#
# Three possibilities:
# 1. MAIN was set on the command line or via user config
# 2. DOCCONF was set on the command line
# 3. MAIN and DOCCONF were _not_ set
#
# Use MAIN_CMDL and DOCCONF_CMDL in the following in order to avoid that
# these get overwritten by chance with values from the DOCCONF files
# (DOCCONF should never be set in a DC file and MAIN_CMDL should always
# overwrite a MAIN setting from DOCCONF)
# The real values will be set when calling recover_cmdl_values

# set DOCCONF_CMDL if DC-file was parsed
[[ -n "$DOCCONF" && -z "$DOCCONF_CMDL" ]] && DOCCONF_CMDL=$DOCCONF

if [[ -z "$DOCCONF_CMDL" && -z "$MAIN_CMDL" ]]; then
# DOCCONF and MAIN were not set on the command line, check other possibilities
    if [[ -n "$DOCCONF_DEFAULT" ]]; then
    # check if a default value was specified in the user/system config file
        if [[ -e $DOCCONF_DEFAULT ]]; then
            sanitize_path "$DOCCONF_DEFAULT" "DOCCONF_CMDL"
            DOC_DIR=$(dirname "$DOCCONF_CMDL")
            if [[ 2 -le $VERBOSITY ]]; then
                echo "Using DOCCONF $DOCCONF_DEFAULT from config files"
            fi
        else
            exit_on_error "DOCCONF_DEFAULT \"$DOCCONF_DEFAULT\" not found in current directory.\nCheck your config file(s)."
        fi
    else
    # try to automatically set DOCCONF
        autoset_docconf
    fi
elif [[ -n "$MAIN_CMDL" ]]; then
    # MAIN was set on the command line or in the user config

    # if MAIN was set on the command line, we are good, path was already
    # checked
    # Checking path in case that a wrong path was specified by the user config
    [[ -e "$MAIN_CMDL" ]] || exit_on_error "MAIN \"$MAIN_CMDL\" that was specified in the config file does not exist"

    # get the source format (XML/ADOC) from MAIN
    SRC_FORMAT=${MAIN_CMDL##*.}
    # Set a DOC_DIR
    DOC_DIR=$(readlink -en "$(dirname "$MAIN_CMDL")")
    DOC_DIR=${DOC_DIR%*/$SRC_FORMAT}
elif [[ -n "$DOCCONF_CMDL" ]]; then
    # check if DOCCONF is a regular file
    if [[ -e $DOCCONF_CMDL ]]; then
        sanitize_path "$DOCCONF_CMDL" "DOCCONF_CMDL"
        DOC_DIR=$(dirname "$DOCCONF_CMDL")
    else
        exit_on_error "The file \"$DOCCONF\" you specified with --docconf is not a valid file"
    fi
fi

#
# Checking MAIN_CMDL, DOCCONF_CMDL, DOC_DIR and DAPSROOT
#
[[ -z "$DOCCONF_CMDL" && -z "$MAIN_CMDL" ]] && exit_on_error "Fatal: Neither \$DOCCONF nor $MAIN are set. This should not have happened. Please report a bug."
[[ -z "$DOC_DIR" ]] && exit_on_error "Fatal: \$DOC_DIR is not set. This should not have happened. Please report a bug."
[[ -z "$DAPSROOT" ]] && exit_on_error "Fatal: \$DAPSROOT is not set. This should not have happened. Please report a bug."

# FINALLY! Parse the DOCCONF file, recover the command line values
[[ -n "$DOCCONF_CMDL" ]] && parse_config "$DOCCONF_CMDL"

# Check if a MAIN has been set
[[ -z "$MAIN" && -z "$MAIN_CMDL" ]] &&  exit_on_error "Fatal: No MAIN file has been set. Please specify one via command line or config file"

# get the source format (XML/ADOC) from MAIN
[[ -z $SRC_FORMAT ]] && SRC_FORMAT=${MAIN##*.}

# Validate SRC_FORMAT - needs to be xml or adoc
[[ "adoc" = "$SRC_FORMAT" || "xml" = "$SRC_FORMAT" ]] || exit_on_error "$MAIN is an unsupported file type (.$SRC_FORMAT)\nmust be AsciiDoc (.adoc) or DocBook (.xml)"

# Check whether "${DOC_DIR}/${SRC_FORMAT}" exists
[[ -d "${DOC_DIR}/${SRC_FORMAT}" ]] || exit_on_error "Source files must reside in  \"${DOC_DIR}/${SRC_FORMAT}/\".\n This directory does not exist."

# Set MAIN if necessary
if [[ -z "$MAIN_CMDL" ]]; then
    # MAIN was provided without any path
    if [[ -e "${DOC_DIR}/${SRC_FORMAT}/$MAIN" ]]; then
        MAIN="${DOC_DIR}/${SRC_FORMAT}/$MAIN"
    # MAIN was provided with a relative path
    elif [[ -e "${DOC_DIR}/$MAIN" ]]; then
        MAIN="${DOC_DIR}/$MAIN"
    # MAIN was provided with an absolute path
    elif [[ "$MAIN" =~ ^/ ]]; then
        # if path to $MAIN does not match DOC_DIR/SRC_FORMAT DC file and MAIN
        # are in different directories, this should not happen
        #
        # In case both match, we can use MAIN as is
        #
        [[ $(dirname $MAIN) = "${DOC_DIR}/${SRC_FORMAT}" ]] || exit_on_error "MAIN and DC-file reside in different base directories, this is not supported:\n\tMAIN: $MAIN\n\tDC-file: $DOCCONF"
    else
        exit_on_error "$MAIN does not exist or does not reside in $DOC_DIR, please check your config"
    fi
else
    MAIN="$MAIN_CMDL"
fi

# FOP/XEP/ASCIIDOC CONFIG AND WRAPPER / JING WRAPPER
# when using a Git checkout, @sysconfdir@ and @pkgdatadir@ have not been
# replaced
#
# ${string/#substring/replacement}
# If $substring matches front end of $string, substitute
# $replacement for $substring.

ADOC_POST_STYLE=${ADOC_POST_STYLE/#@pkgdatadir\@/${DAPSROOT}}
ADOC_SET_STYLE=${ADOC_SET_STYLE/#@pkgdatadir\@/${DAPSROOT}}

FOP_CONFIG_FILE=${FOP_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}
FOP_WRAPPER=${FOP_WRAPPER/#@pkgdatadir\@/${DAPSROOT}}

JING_WRAPPER=${JING_WRAPPER/#@pkgdatadir\@/${DAPSROOT}}

XEP_CONFIG_FILE=${XEP_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}
XEP_WRAPPER=${XEP_WRAPPER/#@pkgdatadir\@/${DAPSROOT}}

XMLFORMAT_CONFIG_FILE=${XMLFORMAT_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}

#
# Now that we are set, recover the command line values one last time and
# check all paths
#
recover_cmdl_values
check_pathlist "$DOC_DIR"

#----------
# Values that need to be exported and are not set in the config
#

# book name

# Backwards compatability:
# In DAPS 3.1 PDFNAME was replaced by OUTPUTNAME. Use the following code
# to stay backwards compatible

if [[ -n "$PDFNAME" && -z "$OUTPUTNAME" ]]; then
    OUTPUTNAME="$PDFNAME"
fi

if [[ -n "$OUTPUTNAME" ]]; then
    export BOOK="$OUTPUTNAME"
else
    if [[ -n "$DOCCONF" ]]; then
        DC_FILE=$(basename "$DOCCONF")
        export BOOK="${DC_FILE#${CONF_PREFIX}*}"
    elif [[ -n "$MAIN_CMDL" ]]; then
        # --main was specified, BOOK is set to basenme of MAIN
        BOOK="$(basename "$MAIN" .${SRC_FORMAT})"
        export BOOK
    fi
fi

# XML_CATALOG_FILES
#
# XML_MAIN_CATALOG is set via config. If it differs from the system setting for
# XML_CATALOG_FILES, add it to XML_CATALOG_FILES (in first place)
#
# Next, check if XML_DEVEL_CATALOG is set. If so, add it to XML_CATALOG_FILES
# (in first place). XML_DEVEL_CATALOG is automatically set by this script when
# working from a Git clone
#
if [[ -n "$XML_CATALOG_FILES" ]]; then
    if [[ $XML_CATALOG_FILES != $XML_MAIN_CATALOG ]]; then
        XML_CATALOG_FILES="$XML_CATALOG_FILES $XML_MAIN_CATALOG"
    fi
else
    XML_CATALOG_FILES="$XML_MAIN_CATALOG"
fi
if [[ -n "$XML_USER_CATALOGS" ]]; then
    XML_CATALOG_FILES="$XML_USER_CATALOGS $XML_CATALOG_FILES"
fi
if [[ -n "$XML_DEVEL_CATALOG" ]]; then
    XML_CATALOG_FILES="$XML_DEVEL_CATALOG $XML_CATALOG_FILES"
fi
export XML_CATALOG_FILES

# ----------------------------------------------------------------------------
# Set paths
#
# set all basic paths that have not been set by now

#----------------------------------
# default BUILD_DIR if not specified elsewhere
[[ -z "$BUILD_DIR" ]] && BUILD_DIR=${DOC_DIR}/build

#----------------------------------
# DocBook Stylesheet and Schema locations (from system or user config file)
# These stylesheets are used as a fallback and/or when no STYLEROOT is
# specified on the command line or the DC file
#
# check whether we have asciidoctor (supports conversion to DocBook 5).
# Set DocBook versions and backends for adoc
#
if [[ "adoc" = "$SRC_FORMAT" ]]; then
    DOCBOOK_VERSION=5
    ADOC_BACKEND=docbook5
    ASCIIDOC=$(which asciidoctor 2>/dev/null)
    if [[ 1 -eq $? ]]; then
        exit_on_error "AsciiDoctor is not installed, you cannot parse AsciiDoc sources."
    fi
else
    DOCBOOK_VERSION=$($XSLTPROC --stylesheet "${DAPSROOT}/daps-xslt/common/get-docbook-version.xsl" --file "$MAIN" "$XSLTPROCESSOR") || exit_on_error "Could not get DocBook version. Maybe $MAIN is not well-formed?"
fi

# DocBook 5
#
if [[ 5 -eq $DOCBOOK_VERSION ]]; then
    # resolve stylesheet URN
    #
    if [[ ${DOCBOOK5_STYLE_URI:0:5} = file: ]]; then
        DOCBOOK_STYLES="$DOCBOOK5_STYLE_URI"
    else
        DOCBOOK_STYLES=$(xmlcatalog "$XML_MAIN_CATALOG" \
          "$DOCBOOK5_STYLE_URI" 2>/dev/null) || \
            exit_on_error "Could not determine the DocBook stylesheet location by resolving \"$DOCBOOK5_STYLE_URI\" via xmlcatalog"
    fi
    # also get the RNG scheme location
    #

    # first check whether we come from a GIT checkout - if so
    # the URI contains @db5version@
    #
    if [[ $DOCBOOK5_RNG_URI =~ [^@]*@db5version\@.* ]]; then
        for DB5_VERSION in "5.1" "5.0"; do
            # checks 5.1 first, if it is found sets DOCBOOK5_RNG and
            # leaves loop via break, otherwise continue with 5.0
            #
            D5U="${DOCBOOK5_RNG_URI/@db5version\@/$DB5_VERSION}"
            DOCBOOK5_RNG=$(xmlcatalog "$XML_MAIN_CATALOG" "$D5U") && break
        done
    else
        if [[ ${DOCBOOK5_RNG_URI:0:5} = file: ]]; then
            DOCBOOK5_RNG="$DOCBOOK5_RNG_URI"
        else
            DOCBOOK5_RNG=$(xmlcatalog "$XML_MAIN_CATALOG" \
              "$DOCBOOK5_RNG_URI" 2>/dev/null) || \
                exit_on_error "Could not determine the DocBook 5 schema location by resolving \"$DOCBOOK5_RNG_URI\" via xmlcatalog"
        fi
    fi
    # remove file:// or file: (Debian, Tumbleweed) prefix
    #
    DOCBOOK5_RNG=${DOCBOOK5_RNG#*file:}
    DOCBOOK5_RNG=${DOCBOOK5_RNG#*//}
    #
    # check if resulting path is valid
    #
    if [[ ! -s "$DOCBOOK5_RNG" ]]; then
        if [[ -n "$DOCBOOK5_RNG_URI_CMDL" ]]; then
            exit_on_error "The URN specified with --schema points to a non-existing file \"$DOCBOOK5_RNG\""
        else
            exit_on_error "The URN specified with DOCBOOK5_RNG_URI points to a non-existing file \"$DOCBOOK5_RNG\""
        fi
    fi

# DocBook 4
#
elif [[ 4 -eq $DOCBOOK_VERSION ]]; then
    # resolve stylesheet URN
    #
    if [[ ${DOCBOOK4_STYLE_URI:0:5} = file: ]]; then
        DOCBOOK_STYLES="$DOCBOOK4_STYLE_URI"
    else
        DOCBOOK_STYLES=$(xmlcatalog "$XML_MAIN_CATALOG" \
          "$DOCBOOK4_STYLE_URI" 2>/dev/null) || \
            exit_on_error "Could not determine the DocBook stylesheet location by resolving \"$DOCBOOK4_STYLE_URI\" via xmlcatalog"
    fi
else
    exit_on_error "Fatal: Could not determine the DocBook version from $MAIN. Looks like $MAIN is not a DocBook 4/5 document."
fi

# remove the file:// or file: (Debian, Tumbleweed) string from the styles
# use ##*file:// rather than #file:// because sometimes xmlcatalog also outputs
# warnings to stdout which we would like to ignore. Fortunately, the file:// URL
# is always the last string
#
# Is there a better way to do this with shell built-ins?
#
DOCBOOK_STYLES=${DOCBOOK_STYLES##*file:}
DOCBOOK_STYLES=${DOCBOOK_STYLES#*//}
DOCBOOK_STYLES=${DOCBOOK_STYLES%/}

#
# Check resulting path
#
[[ -d "$DOCBOOK_STYLES" ]] || exit_on_error "DOCBOOK4_STYLE_URI or DOCBOOK5_STYLE_URI points to a non-existing directory \"$DOCBOOK_STYLES\"."

# ----------------------------------------------------------------------------
# Determine whether profiling is turned on and if so, set PROFILE_URN
#
# This needs to be done in make/common_variables.mk to allow passing
# profiling variable via command line to make:
# daps -d DC-foo profile PROFCONDITION=foobar
# PROFCONDITION=foobar is directly passed on to make and therefore is
# not known here

#----------------------------------
# Result directory / LOG directory
#
R_DIR="${BUILD_DIR}/${BOOK}"
LOG_DIR="${R_DIR}/log"

#-------------------------------------------------------------------
# Now export all variables set by the config file
export "${VARLIST[@]}"

#-------------------------------------------------------------------
# Create a temporary file for SETFILES (setfiles.mk)
# this needs to be done here, otherwise it is impossible to
# delete the file after the script has run
#
SETFILES_TMP=$(mktemp -q --tmpdir daps_setfiles.XXXXXXXX 2>/dev/null) || exit_on_error "Could not write temporary SETFILES file."
export SETFILES_TMP

#-------------------------------------------------------------------
# Create XML from AsciiDoc
#
if [[ "adoc" = "$SRC_FORMAT" ]]; then
    ADOC_MAIN="$MAIN"
    ADOC_DIR="${BUILD_DIR}/.adoc"
    MAIN="${ADOC_DIR}/${BOOK}.xml"

    # make the path for ADOC_IMG_DIR absolute if a relative path was
    # provided by config file
    #
    if [[ -z $ADOC_IMG_DIR_CMDL ]]; then
        # path was not provided on cmdl
        if [[ -n $ADOC_IMG_DIR ]]; then
            # path was provided by config
            # if not absolute, prepend DOC_DIR
            [[ ! "/" == ${ADOC_IMG_DIR:1} ]] && ADOC_IMG_DIR="$DOC_DIR/$ADOC_IMG_DIR"
            #  error out if $DOC_DIR/$ADOC_IMG_DIR does not exist
            [[ ! -d $ADOC_IMG_DIR ]] && exit_on_error "AsciiDoc image directory $ADOC_IMG_DIR does not exist"
        fi
    fi
    export ADOC_IMG_DIR ADOC_MAIN ADOC_DIR MAIN
    [[ 1 -eq $FORCE_REBUILD ]] && MOPTS="--always-make"
    [[ 2 -gt $VERBOSITY ]] && MOPTS="$MOPTS --silent"

    make $MOPTS -f $DAPSROOT/make/adoc2xml.mk  || exit_on_error "\nConverting the AsciiDoc sources to XML caused a fatal error.\nCheck the $(basename ${ASCIIDOC}) message above for details."
fi

#-------------------------------------------------------------------
# Check whether the document is _well-formed_ (but not whether they
# it is valid). If it is not, exit and display an error message.
# Works for both DocBook 4 and DocBook 5, as we are only checking for
# well-formedness and not for validity (a DocBook 5 validity check would
# require jing).

CHECK_WELLFORMED=$(PYTHONWARNINGS="ignore" ${LIBEXEC_DIR}/daps-xmlwellformed --xinclude ${MAIN} 2>&1)

if [[ 0 -ne $? ]]; then
    # sometimes daps-xmnlwellformed stumbles upon errors and does not produce
    # any error text (e.g. on a missing entities file)
    # Let's ignore these cases and hope for the best
    # (these errors will get caught in the validation check)
    if [[ -n "$CHECK_WELLFORMED" ]]; then
    ccecho "error" "Fatal error:\n$CHECK_WELLFORMED"
    exit 1
    fi
fi

#-------------------------------------------------------------------
# Finally, run the Subcommands
#

# source additional functions
#
[[ -f $LIB_DIR/$SUBCMD ]] && source "$LIB_DIR/$SUBCMD"

# By default we want to write a log file, can be overwritten by
# subcommand function
#
WRITE_LOG=1

# Quoting needs to be exactly like this, do not change
#
${SUBCOMMANDS[$SUBCMD]} "$SUBCMD" "${SCMD_ARGS[@]}"

# remove the tmp SETFILE
# done via trap, see above

exit;