summaryrefslogtreecommitdiff
path: root/scripts/functions
blob: 2331557be4572a07f61d4f463795014b1d212eec (plain)
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
# -*- mode: sh; tab-width: 4 -*-
# vi: ts=4:sw=4:sts=4:et
# This file contains some useful common functions
# Copyright 2007 Yann E. MORIN
# Licensed under the GPL v2. See COPYING in the root of this package

# Prepare the fault handler
CT_OnError() {
    local ret=$?
    local result
    local old_trap
    local intro
    local file line func
    local step step_depth

    # To avoid printing the backtace for each sub-shell
    # up to the top-level, just remember we've dumped it
    if [ ! -f "${CT_WORK_DIR}/backtrace" ]; then
        [ -d "${CT_WORK_DIR}" ] && touch "${CT_WORK_DIR}/backtrace"

        # Print steps backtrace
        step_depth=${CT_STEP_COUNT}
        CT_STEP_COUNT=1     # To have a zero-indentation
        CT_DoLog ERROR ""
        CT_DoLog ERROR ">>"
        intro="Build failed"
        for((step=step_depth; step>0; step--)); do
            CT_DoLog ERROR ">>  ${intro} in step '${CT_STEP_MESSAGE[${step}]}'"
            intro="      called"
        done

        # Print functions backtrace
        intro="Error happened in"
        CT_DoLog ERROR ">>"
        for((depth=1; ${BASH_LINENO[$((${depth}-1))]}>0; depth++)); do
            file="${BASH_SOURCE[${depth}]#${CT_LIB_DIR}/}"
            func="${FUNCNAME[${depth}]}"
            line="@${BASH_LINENO[${depth}-1]:-?}"
            CT_DoLog ERROR ">>  ${intro}: ${func}[${file}${line}]"
            intro="      called from"
        done

        # If the user asked for interactive debugging, dump him/her to a shell
        if [ "${CT_DEBUG_INTERACTIVE}" = "y" ]; then
            # We do not want this sub-shell exit status to be caught, because
            # it is absolutely legit that it exits with non-zero.
            # Save the trap handler to restore it after our debug-shell
            old_trap="$(trap -p ERR)"
            trap -- ERR
            (
                exec >&6 2>&7 <&8
                printf "\r         \n\nCurrent command"
                if [ -n "${cur_cmd}" ]; then
                    printf ":\n  %s\n" "${cur_cmd}"
                else
                    printf " (unknown), "
                fi
                printf "exited with error code: %d\n" ${ret}
                printf "Please fix it up and finish by exiting the shell with one of these values:\n"
                printf "    1  fixed, continue with next build command\n"
                if [ -n "${cur_cmd}" ]; then
                    printf "    2  repeat this build command\n"
                fi
                printf "    3  abort build\n\n"
                while true; do
                    ${bash} --rcfile <(printf "PS1='ct-ng:\w> '\nPROMPT_COMMAND=''\n") -i
                    result=$?
                    case $result in
                        1)  printf "\nContinuing past the failed command.\n\n"
                            break
                            ;;
                        2)  if [ -n "${cur_cmd}" ]; then
                                printf "\nRe-trying last command.\n\n"
                                break
                            fi
                            ;;
                        3)  break;;
                    esac
                    printf "\nPlease exit with one of these values:\n"
                    printf "    1  fixed, continue with next build command\n"
                    if [ -n "${cur_cmd}" ]; then
                        printf "    2  repeat this build command\n"
                    fi
                    printf "    3  abort build\n"
                done
                exit $result
            )
            result=$?
            # Restore the trap handler
            eval "${old_trap}"
            case "${result}" in
                1)  rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/skip"; return;;
                2)  rm -f "${CT_WORK_DIR}/backtrace"; touch "${CT_BUILD_DIR}/repeat"; return;;
                # 3 is an abort, continue...
            esac
        fi
    fi

    # And finally, in top-level shell, print some hints
    if [ ${BASH_SUBSHELL} -eq 0 ]; then
        # Help diagnose the error
        CT_STEP_COUNT=1     # To have a zero-indentation
        CT_DoLog ERROR ">>"
        if [ "${CT_LOG_TO_FILE}" = "y" ]; then
            CT_DoLog ERROR ">>  For more info on this error, look at the file: '${tmp_log_file#${CT_TOP_DIR}/}'"
        fi
        CT_DoLog ERROR ">>  There is a list of known issues, some with workarounds, in:"
        CT_DoLog ERROR ">>      '${CT_DOC_DIR#${CT_TOP_DIR}/}/B - Known issues.txt'"

        CT_DoLog ERROR ""
        CT_DoEnd ERROR
        rm -f "${CT_WORK_DIR}/backtrace"
    fi
    exit $ret
}

# Install the fault handler
trap CT_OnError ERR

# Inherit the fault handler in subshells and functions
set -E

# Make pipes fail on the _first_ failed command
# Not supported on bash < 3.x, but we need it, so drop the obsoleting bash-2.x
set -o pipefail

# Don't hash commands' locations, and search every time it is requested.
# This is slow, but needed because of the static/shared core gcc which shall
# always match to shared if it exists, and only fallback to static if the
# shared is not found
set +o hashall

# Log policy:
#  - first of all, save stdout so we can see the live logs: fd #6
# (also save stdin and stderr for use by CT_DEBUG_INTERACTIVE)
exec 6>&1 7>&2 8<&0
#  - then point stdout to the log file
tmp_log_file="${CT_TOP_DIR}/build.log"
rm -f "${tmp_log_file}"
exec >>"${tmp_log_file}"

# The different log levels:
CT_LOG_LEVEL_ERROR=0
CT_LOG_LEVEL_WARN=1
CT_LOG_LEVEL_INFO=2
CT_LOG_LEVEL_EXTRA=3
CT_LOG_LEVEL_CFG=4
CT_LOG_LEVEL_FILE=5
CT_LOG_LEVEL_STATE=6
CT_LOG_LEVEL_ALL=7
CT_LOG_LEVEL_DEBUG=8

# Make it easy to use \n and !
CR=$(printf "\n")
BANG='!'

# A function to log what is happening
# Different log level are available:
#   - ERROR:   A serious, fatal error occurred
#   - WARN:    A non fatal, non serious error occurred, take your responsbility with the generated build
#   - INFO:    Informational messages
#   - EXTRA:   Extra informational messages
#   - CFG:     Output of various "./configure"-type scripts
#   - FILE:    File / archive unpacking.
#   - STATE:   State save & restore
#   - ALL:     Component's build messages
#   - DEBUG:   Internal debug messages
# Usage: CT_DoLog <level> [message]
# If message is empty, then stdin will be logged.
CT_DoLog() {
    local max_level LEVEL level cur_l cur_L
    local l
    eval max_level="\${CT_LOG_LEVEL_${CT_LOG_LEVEL_MAX}}"
    # Set the maximum log level to DEBUG if we have none
    [ -z "${max_level}" ] && max_level=${CT_LOG_LEVEL_DEBUG}

    LEVEL="$1"; shift
    eval level="\${CT_LOG_LEVEL_${LEVEL}}"

    if [ $# -eq 0 ]; then
        cat -
    else
        echo -e "${*}"
    fi |( IFS="${CR}" # We want the full lines, even leading spaces
          _prog_bar_cpt=0
          _prog_bar[0]='/'
          _prog_bar[1]='-'
          _prog_bar[2]='\'
          _prog_bar[3]='|'
          indent=$((2*CT_STEP_COUNT))
          while read line; do
              case "${CT_LOG_SEE_TOOLS_WARN},${line}" in
                y,*"warning:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
                y,*"WARNING:"*)         cur_L=WARN; cur_l=${CT_LOG_LEVEL_WARN};;
                *"error:"*)             cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
                *"make["*"]: *** ["*)   cur_L=ERROR; cur_l=${CT_LOG_LEVEL_ERROR};;
                *)                      cur_L="${LEVEL}"; cur_l="${level}";;
              esac
              # There will always be a log file (stdout, fd #1), be it /dev/null
              printf "[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}"
              if [ ${cur_l} -le ${max_level} ]; then
                  # Only print to console (fd #6) if log level is high enough.
                  printf "${CT_LOG_PROGRESS_BAR:+\r}[%-5s]%*s%s%s\n" "${cur_L}" "${indent}" " " "${line}" >&6
              fi
              if [ "${CT_LOG_PROGRESS_BAR}" = "y" ]; then
                  printf "\r[%02d:%02d] %s " $((SECONDS/60)) $((SECONDS%60)) "${_prog_bar[$((_prog_bar_cpt/10))]}" >&6
                  _prog_bar_cpt=$(((_prog_bar_cpt+1)%40))
              fi
          done
        )

    return 0
}

# Execute an action, and log its messages
# It is possible to even log local variable assignments (a-la: var=val ./cmd opts)
# Usage: CT_DoExecLog <level> [VAR=val...] <command> [parameters...]
CT_DoExecLog() {
    local level="$1"
    local cur_cmd
    local ret
    shift
    (
    for i in "$@"; do
        cur_cmd+="'${i}' "
    done
    while true; do
        case "${1}" in
            *=*)    eval export "'${1}'"; shift;;
            *)      break;;
        esac
    done
    # This while-loop goes hand-in-hand with the ERR trap handler:
    # - if the command terminates successfully, then we hit the break
    #   statement, and we exit the loop
    # - if the command terminates in error, then the ERR handler kicks
    #   in, then:
    #     - if the user did *not* ask for interactive debugging, the ERR
    #       handler exits, and we hit the end of the sub-shell
    #     - if the user did ask for interactive debugging, the ERR handler
    #       spawns a shell. Upon termination of this shell, the ERR handler
    #       examines the exit status of the shell:
    #         - if 1, the ERR handler returns; then we hit the else statement,
    #           then the break, and we exit the 'while' loop, to continue the
    #           build;
    #         - if 2, the ERR handler touches the repeat file, and returns;
    #           then we hit the if statement, and we loop for one more
    #           iteration;
    #         - if 3, the ERR handler exits with the command's exit status,
    #           and we're dead;
    #         - for any other exit status of the shell, the ERR handler
    #           prints an informational message, and respawns the shell
    #
    # This allows a user to get an interactive shell that has the same
    # environment (PATH and so on) that the failed command was ran with.
    while true; do
        rm -f "${CT_BUILD_DIR}/repeat"
        CT_DoLog DEBUG "==> Executing: ${cur_cmd}"
        "${@}" 2>&1 |CT_DoLog "${level}"
        ret="${?}"
        if [ -f "${CT_BUILD_DIR}/repeat" ]; then
            rm -f "${CT_BUILD_DIR}/repeat"
            continue
        elif [ -f "${CT_BUILD_DIR}/skip" ]; then
            rm -f "${CT_BUILD_DIR}/skip"
            ret=0
            break
        else
            break
        fi
    done
    exit ${ret}
    )
    # Catch failure of the sub-shell
    [ $? -eq 0 ]
}

# Tail message to be logged whatever happens
# Usage: CT_DoEnd <level>
CT_DoEnd()
{
    local level="$1"
    CT_STOP_DATE=$(CT_DoDate +%s%N)
    CT_STOP_DATE_HUMAN=$(CT_DoDate +%Y%m%d.%H%M%S)
    if [ "${level}" != "ERROR" ]; then
        CT_DoLog "${level:-INFO}" "Build completed at ${CT_STOP_DATE_HUMAN}"
    fi
    elapsed=$((CT_STOP_DATE-CT_STAR_DATE))
    elapsed_min=$((elapsed/(60*1000*1000*1000)))
    elapsed_sec=$(printf "%02d" $(((elapsed%(60*1000*1000*1000))/(1000*1000*1000))))
    elapsed_csec=$(printf "%02d" $(((elapsed%(1000*1000*1000))/(10*1000*1000))))
    CT_DoLog ${level:-INFO} "(elapsed: ${elapsed_min}:${elapsed_sec}.${elapsed_csec})"
}

# Remove entries referring to . and other relative paths
# Usage: CT_SanitizePath
CT_SanitizePath() {
    local new
    local p
    local IFS=:
    for p in $PATH; do
        # Only accept absolute paths;
        # Note: as a special case the empty string in PATH is equivalent to .
        if [ -n "${p}" -a -z "${p%%/*}" ]; then
            new="${new}${new:+:}${p}"
        fi
    done
    PATH="${new}"
}

# Sanitize the directory name contained in the variable passed as argument:
# - remove duplicate /
# - remove . (current dir) at the beginning, in the middle or at the end
# - resolve .. (parent dir) if there is a previous component
# - remove .. (parent dir) if at the root
#
# Usage: CT_SanitizeVarDir CT_PREFIX_DIR
CT_SanitizeVarDir() {
    local var
    local old_dir
    local new_dir tmp

    for var in "$@"; do
        eval "old_dir=\"\${${var}}\""
        new_dir=$( echo "${old_dir}" | ${awk} '
{
    isabs = $1 == "" # Started with a slash
    trail = $NF == "" # Ending with a slash
    ncomp = 0 # Components in a path so far
    for (i = 1; i <= NF; i++) {
        # Double-slash or current dir? Ignore
        if ($i == "" || $i == ".") {
            continue;
        }
        # .. pops the last component unless it is at the beginning
        if ($i == ".." && ncomp != 0 && comps[ncomp] != "..") {
            ncomp--;
            continue;
        }
        comps[++ncomp] = $i;
    }
    seencomp = 0
    for (i = 1; i <= ncomp; i++) {
        if (comps[i] == ".." && isabs) {
            # /../ at the beginning is equivalent to /
            continue;
        }
        printf "%s%s", isabs || i != 1 ? "/" : "", comps[i];
        seencomp = 1;
    }
    if (!seencomp && !isabs && !trail) {
        # Eliminated all components, but no trailing slash -
        # if the result is appened with /foo, must not become absolute
        printf ".";
    }
    if ((!seencomp && isabs) || (seencomp && trail)) {
        printf "/";
    }
}' FS=/ )
        eval "${var}=\"${new_dir}\""
        CT_DoLog DEBUG "Sanitized '${var}': '${old_dir}' -> '${new_dir}'"
    done
}

# Abort the execution with an error message
# Usage: CT_Abort <message>
CT_Abort() {
    CT_DoLog ERROR "$1"
    false
}

# Test a condition, and print a message if satisfied
# Usage: CT_Test <message> <tests>
CT_Test() {
    local ret
    local m="$1"
    shift
    CT_DoLog DEBUG "Testing '! ( $* )'"
    test "$@" && CT_DoLog WARN "$m"
    return 0
}

# Test a condition, and abort with an error message if satisfied
# Usage: CT_TestAndAbort <message> <tests>
CT_TestAndAbort() {
    local m="$1"
    shift
    CT_DoLog DEBUG "Testing '! ( $* )'"
    test "$@" && CT_Abort "$m"
    return 0
}

# Test a condition, and abort with an error message if not satisfied
# Usage: CT_TestAndAbort <message> <tests>
CT_TestOrAbort() {
    local m="$1"
    shift
    CT_DoLog DEBUG "Testing '$*'"
    test "$@" || CT_Abort "$m"
    return 0
}

# Test the presence of a tool, or abort if not found
# Usage: CT_HasOrAbort <tool>
CT_HasOrAbort() {
    CT_TestAndAbort "'${1}' not found and needed for successful toolchain build." -z "$(CT_Which "${1}")"
    return 0
}

# Search a program: wrap "which" for those system where "which"
# verbosely says there is no match (such as on Mandriva).
# Usage: CT_Which <filename>
CT_Which() {
  which "$1" 2>/dev/null || true
}

# Get current date with nanosecond precision
# On those system not supporting nanosecond precision, faked with rounding down
# to the highest entire second
# Usage: CT_DoDate <fmt>
CT_DoDate() {
    date "$1" |${sed} -r -e 's/%?N$/000000000/;'
}

CT_STEP_COUNT=1
CT_STEP_MESSAGE[${CT_STEP_COUNT}]="(top-level)"
# Memorise a step being done so that any error is caught
# Usage: CT_DoStep <loglevel> <message>
CT_DoStep() {
    local start=$(CT_DoDate +%s%N)
    CT_DoLog "$1" "================================================================="
    CT_DoLog "$1" "$2"
    CT_STEP_COUNT=$((CT_STEP_COUNT+1))
    CT_STEP_LEVEL[${CT_STEP_COUNT}]="$1"; shift
    CT_STEP_START[${CT_STEP_COUNT}]="${start}"
    CT_STEP_MESSAGE[${CT_STEP_COUNT}]="$1"
    return 0
}

# End the step just being done
# Usage: CT_EndStep
CT_EndStep() {
    local stop=$(CT_DoDate +%s%N)
    local duration=$(printf "%032d" $((stop-${CT_STEP_START[${CT_STEP_COUNT}]})) \
                     |${sed} -r -e 's/([[:digit:]]{2})[[:digit:]]{7}$/\.\1/; s/^0+//; s/^\./0\./;'
                    )
    local elapsed=$(printf "%02d:%02d" $((SECONDS/60)) $((SECONDS%60)))
    local level="${CT_STEP_LEVEL[${CT_STEP_COUNT}]}"
    local message="${CT_STEP_MESSAGE[${CT_STEP_COUNT}]}"
    CT_STEP_COUNT=$((CT_STEP_COUNT-1))
    CT_DoLog "${level}" "${message}: done in ${duration}s (at ${elapsed})"
    return 0
}

# Pushes into a directory, and pops back
CT_Pushd() {
    CT_DoLog DEBUG "Entering '$1'"
    pushd "$1" >/dev/null 2>&1
}
CT_Popd() {
    popd >/dev/null 2>&1
}

# Create a dir and cd or pushd into it
# Usage: CT_mkdir_cd <dir/to/create>
#        CT_mkdir_pushd <dir/to/create>
CT_mkdir_cd() {
    local dir="${1}"

    mkdir -p "${dir}"
    cd "${dir}"
}
CT_mkdir_pushd() {
    local dir="${1}"

    mkdir -p "${dir}"
    CT_Pushd "${dir}"
}

# Creates a temporary directory
# $1: variable to assign to
# Usage: CT_MktempDir foo
CT_MktempDir() {
    # Some mktemp do not allow more than 6 Xs
    eval "$1"=$(mktemp -q -d "${CT_BUILD_DIR}/tmp.XXXXXX")
    CT_TestOrAbort "Could not make temporary directory" -n "${!1}" -a -d "${!1}"
    CT_DoLog DEBUG "Made temporary directory '${!1}'"
    return 0
}

# Removes one or more directories, even if it is read-only, or its parent is
# Usage: CT_DoForceRmdir dir [...]
CT_DoForceRmdir() {
    local dir
    local mode
    for dir in "${@}"; do
        [ -d "${dir}" ] || continue
        case "$CT_SYS_OS" in
            Linux|CYGWIN*)
                mode="$(stat -c '%a' "$(dirname "${dir}")")"
                ;;
            Darwin|*BSD)
                mode="$(stat -f '%Lp' "$(dirname "${dir}")")"
                ;;
            *)
                CT_Abort "Unhandled host OS $CT_SYS_OS"
                ;;
        esac
        CT_DoExecLog ALL chmod u+w "$(dirname "${dir}")"
        CT_DoExecLog ALL chmod -R u+w "${dir}"
        CT_DoExecLog ALL rm -rf "${dir}"
        CT_DoExecLog ALL chmod ${mode} "$(dirname "${dir}")"
    done
}

# Echoes the specified string on stdout until the pipe breaks.
# Doesn't fail
# $1: string to echo
# Usage: CT_DoYes "" |${make} oldconfig
CT_DoYes() {
    yes "$1" || true
}

# Add the specified directory to LD_LIBRARY_PATH, and export it
# If the specified patch is already present, just export
# $1: path to add
# $2: add as 'first' or 'last' path, 'first' is assumed if $2 is empty
# Usage CT_SetLibPath /some/where/lib [first|last]
CT_SetLibPath() {
    local path="$1"
    local pos="$2"

    case ":${LD_LIBRARY_PATH}:" in
        *:"${path}":*)  ;;
        *)  case "${pos}" in
                last)
                    CT_DoLog DEBUG "Adding '${path}' at end of LD_LIBRARY_PATH"
                    LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}${path}"
                    ;;
                first|"")
                    CT_DoLog DEBUG "Adding '${path}' at start of LD_LIBRARY_PATH"
                    LD_LIBRARY_PATH="${path}${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}"
                    ;;
                *)
                    CT_Abort "Incorrect position '${pos}' to add '${path}' to LD_LIBRARY_PATH"
                    ;;
            esac
            ;;
    esac
    CT_DoLog DEBUG "==> LD_LIBRARY_PATH='${LD_LIBRARY_PATH}'"
    export LD_LIBRARY_PATH
}

# Build up the list of allowed tarball extensions
# Add them in the prefered order; most preferred comes first
CT_DoListTarballExt() {
    if [ "${CT_CONFIGURE_has_xz}" = "y" ]; then
        printf ".tar.xz\n"
    fi
    if [    "${CT_CONFIGURE_has_lzma}" = "y"    \
         -o "${CT_CONFIGURE_has_xz}" = "y" ]; then
        printf ".tar.lzma\n"
    fi
    printf ".tar.bz2\n"
    printf ".tar.gz\n.tgz\n"
    printf ".tar\n"
    printf ".zip\n"
}

# Get the file name extension of a component
# Usage: CT_GetFileExtension <component_name-component_version> [extension]
# If found, echoes the extension to stdout, and return 0
# If not found, echoes nothing on stdout, and return !0.
CT_GetFileExtension() {
    local ext
    local file="$1"
    shift
    local first_ext="$1"

    # we need to also check for an empty extension for those very
    # peculiar components that don't have one (such as sstrip from
    # buildroot).
    for ext in ${first_ext} $(CT_DoListTarballExt) /.git ''; do
        if [ -e "${CT_TARBALLS_DIR}/${file}${ext}" -o -L  "${CT_TARBALLS_DIR}/${file}${ext}" ]; then
            echo "${ext}"
            exit 0
        fi
    done

    exit 1
}

# Try to retrieve the specified URL (HTTP or FTP)
# Usage: CT_DoGetFile <URL>
# This functions always returns true (0), as it can be legitimate not
# to find the requested URL (think about snapshots, different layouts
# for different gcc versions, etc...).
CT_DoGetFile() {
    local url="${1}"
    local dest="${CT_TARBALLS_DIR}/${url##*/}"
    local tmp="${dest}.tmp-dl"

    # Remove potential left-over from a previous run
    rm -f "${tmp}"

    # We also retry a few times, in case there is a transient error (eg. behind
    # a dynamic IP that changes during the transfer...)
    # With automated download as we are doing, it can be very dangerous to
    # continue the downloads. It's far better to simply overwrite the
    # destination file.
    # Some company networks have firewalls to connect to the internet, but it's
    # not easy to detect them, so force a global ${CT_CONNECT_TIMEOUT}-second
    # timeout.
    if [ ${CT_CONNECT_TIMEOUT} = -1 ]; then
        T=
    else
        T="-T ${CT_CONNECT_TIMEOUT}"
    fi
    if CT_DoExecLog ALL wget --passive-ftp --tries=3 -nc    \
                             --progress=dot:binary          \
                             ${T}                           \
                             -O "${tmp}"                    \
                             "${url}"
    then
        # Success, we got it, good!
        mv "${tmp}" "${dest}"
        CT_DoLog DEBUG "Got it from: \"${url}\""
    else
        # Woops...
        rm -f "${tmp}"
        CT_DoLog DEBUG "Not at this location: \"${url}\""
    fi
}

# This function tries to retrieve a tarball form a local directory
# Usage: CT_GetLocal <basename> [.extension]
CT_GetLocal() {
    local basename="$1"
    local first_ext="$2"
    local ext

    # Do we already have it in *our* tarballs dir?
    if ext="$( CT_GetFileExtension "${basename}" ${first_ext} )"; then
        CT_DoLog DEBUG "Already have '${basename}'"
        return 0
    fi

    if [ -n "${CT_LOCAL_TARBALLS_DIR}" ]; then
        CT_DoLog DEBUG "Trying to retrieve an already downloaded copy of '${basename}'"
        # We'd rather have a bzip2'ed tarball, then gzipped tarball, plain tarball,
        # or, as a failover, a file without extension.
        for ext in ${first_ext} $(CT_DoListTarballExt) ''; do
            CT_DoLog DEBUG "Trying '${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}'"
            if [ -r "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" -a \
                 "${CT_FORCE_DOWNLOAD}" != "y" ]; then
                CT_DoLog DEBUG "Got '${basename}' from local storage"
                CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}${ext}" "${CT_TARBALLS_DIR}/${basename}${ext}"
                return 0
            fi
        done
    fi
    return 1
}

# This function gets the custom source from either a tarball or directory
# Usage: CT_GetCustom <name> <version> <location>
CT_GetCustom() {
    local component_name="$1"
    local component_version="$2"
    local component_location="$3"

    # Some local variables we use to help us figure out what to do
    local component_location_type="dir" # str: 'file' or 'dir'
    local component_location_filename="" # filename... if it's a file

    CT_TestAndAbort \
        "${component_name}: Custom location setting is empty" \
        -z "${component_location}"

    CT_TestAndAbort \
        "${component_name}: Custom version setting is empty" \
        -z "${component_version}"

    if [ -f "${component_location}" ]; then
        component_location_type="file"
        component_location_filename="$(basename ${component_location})"
    elif [ -d "${component_location}" ]; then
        # Yes, it's the default, but it rules out the else case in the `if'.
        component_location_type="dir"
        # as -d and -f say: it's a <directory|file> and is readable!
    else
        CT_Abort "${component_name}: Unable to read ${component_location}, make sure the setting is correct and double check the permissions!"
    fi

    if [ "${component_location_type}" = "file" ]; then
        CT_DoLog EXTRA "Got '${component_location}' from custom location"
        # We need to know the custom tarball extension,
        # so we can create a properly-named symlink, which
        # we use later on in 'extract'
        case "${component_location}" in
            *.tar.xz|*.tar.bz2|*.tar.lzma|*.tar.gz|*.tgz|*.tar|*.zip) ;;
            *) CT_Abort "Unknown extension for custom tarball '${component_location}'" ;;
        esac
        [ ! -L "${CT_TARBALLS_DIR}/${component_location_filename}" ] && \
            CT_DoExecLog DEBUG ln -sf "${component_location}" \
            "${CT_TARBALLS_DIR}/${component_location_filename}"
    elif [ "${component_location_type}" = "dir" ]; then
        CT_DoLog EXTRA "Got '${component_location}' from custom location"
        [ ! -d "${CT_SRC_DIR}/${component_name}-${component_version}" ] && \
            CT_DoExecLog DEBUG ln -sf "${component_location}" \
            "${CT_SRC_DIR}/${component_name}-${component_version}"

        # Don't try to extract from source directory, it's extracted!
        touch "${CT_SRC_DIR}/.${component_name}-${component_version}.extracted"
    fi
    # Don't patch a custom source, it's custom!
    touch "${CT_SRC_DIR}/.${component_name}-${component_version}.patched"
}

# This function saves the specified to local storage if possible,
# and if so, symlinks it for later usage
# Usage: CT_SaveLocal </full/path/file.name>
CT_SaveLocal() {
    local file="$1"
    local basename="${file##*/}"

    if [ "${CT_SAVE_TARBALLS}" = "y" ]; then
        CT_DoLog EXTRA "Saving '${basename}' to local storage"
        # The file may already exist if downloads are forced: remove it first
        CT_DoExecLog ALL rm -f "${CT_LOCAL_TARBALLS_DIR}/${basename}"
        CT_DoExecLog ALL mv -f "${file}" "${CT_LOCAL_TARBALLS_DIR}"
        CT_DoExecLog ALL ln -s "${CT_LOCAL_TARBALLS_DIR}/${basename}" "${file}"
    fi
}

# Download the file from one of the URLs passed as argument
# Usage: CT_GetFile <basename> [.extension] <url> [url ...]
CT_GetFile() {
    local ext
    local -a URLS
    local url
    local file="$1"
    local first_ext
    shift
    # If next argument starts with a dot, then this is not an URL,
    # and we can consider that it is a preferred extension.
    case "$1" in
        .*) first_ext="$1"
            shift
            ;;
    esac

    # Does it exist localy?
    if CT_GetLocal "${file}" ${first_ext}; then
        return 0
    fi
    # No, it does not...

    # If not allowed to download from the Internet, don't
    if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
        CT_DoLog DEBUG "Not allowed to download from the Internet, aborting ${file} download"
        return 1
    fi

    # Try to retrieve the file
    CT_DoLog EXTRA "Retrieving '${file}'"

    # Add URLs on the LAN mirror
    if [ "${CT_USE_MIRROR}" = "y" ]; then
        CT_TestOrAbort "Please set the mirror base URL" -n "${CT_MIRROR_BASE_URL}"
        URLS+=( "${CT_MIRROR_BASE_URL}/${file%-*}" )
        URLS+=( "${CT_MIRROR_BASE_URL}" )
    fi

    if [ "${CT_FORCE_MIRROR}" != "y" ]; then
        URLS+=( "${@}" )
    fi

    # Scan all URLs in turn, and try to grab a tarball from there
    # Do *not* try git trees (ext=/.git), this is handled in a specific
    # wrapper, below
    for ext in ${first_ext} $(CT_DoListTarballExt) ''; do
        # Try all urls in turn
        for url in "${URLS[@]}"; do
            [ -n "${url}" ] || continue
            CT_DoLog DEBUG "Trying '${url}/${file}${ext}'"
            CT_DoGetFile "${url}/${file}${ext}"
            if [ -f "${CT_TARBALLS_DIR}/${file}${ext}" ]; then
                CT_DoLog DEBUG "Got '${file}' from the Internet"
                CT_SaveLocal "${CT_TARBALLS_DIR}/${file}${ext}"
                return 0
            fi
        done
    done

    # Just return error, someone may want to catch and handle the error
    # (eg. glibc add-ons can be missing).
    return 1
}

# Checkout from CVS, and build the associated tarball
# The tarball will be called ${basename}.tar.bz2
# Prerequisite: either the server does not require password,
# or the user must already be logged in.
# 'tag' is the tag to retrieve. Must be specified, but can be empty.
# If dirname is specified, then module will be renamed to dirname
# prior to building the tarball.
# Usage: CT_GetCVS <basename> <url> <module> <tag> [dirname[=subdir]]
# Note: if '=subdir' is given, then it is used instead of 'module'.
CT_GetCVS() {
    local basename="$1"
    local uri="$2"
    local module="$3"
    local tag="${4:+-r ${4}}"
    local dirname="$5"
    local tmp_dir

    # First try locally, then the mirror
    if CT_GetFile "${basename}"; then
        # Got it! Return early! :-)
        return 0
    fi

    if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
        CT_DoLog WARN "Downloads forbidden, not trying cvs retrieval"
        return 1
    fi

    CT_MktempDir tmp_dir
    CT_Pushd "${tmp_dir}"

    CT_DoExecLog ALL cvs -z 9 -d "${uri}" co -P ${tag} "${module}"
    if [ -n "${dirname}" ]; then
        case "${dirname}" in
            *=*)
                CT_DoExecLog DEBUG mv "${dirname#*=}" "${dirname%%=*}"
                CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname%%=*}"
                ;;
            *)
                CT_DoExecLog ALL mv "${module}" "${dirname}"
                CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${dirname:-${module}}"
                ;;
        esac
    fi
    CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"

    CT_Popd
    CT_DoExecLog ALL rm -rf "${tmp_dir}"
}

# Check out from SVN, and build the associated tarball
# The tarball will be called ${basename}.tar.bz2
# Prerequisite: either the server does not require password,
# or the user must already be logged in.
# 'rev' is the revision to retrieve
# Usage: CT_GetSVN <basename> <url> [rev]
CT_GetSVN() {
    local basename="$1"
    local uri="$2"
    local rev="$3"

    # First try locally, then the mirror
    if CT_GetFile "${basename}"; then
        # Got it! Return early! :-)
        return 0
    fi

    if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
        CT_DoLog WARN "Downloads forbidden, not trying svn retrieval"
        return 1
    fi

    CT_MktempDir tmp_dir
    CT_Pushd "${tmp_dir}"

    if ! CT_DoExecLog ALL svn export ${rev:+-r ${rev}} "${uri}" "${basename}"; then
        CT_DoLog WARN "Could not retrieve '${basename}'"
        return 1
    fi
    CT_DoExecLog ALL tar cjf "${CT_TARBALLS_DIR}/${basename}.tar.bz2" "${basename}"
    CT_SaveLocal "${CT_TARBALLS_DIR}/${basename}.tar.bz2"

    CT_Popd
    CT_DoExecLog ALL rm -rf "${tmp_dir}"
}

# Clone a git tree
# Tries the given URLs in turn until one can get cloned. No tarball will be created.
# Prerequisites: either the server does not require password,
# or the user has already taken any action to authenticate to the server.
# The cloned tree will *not* be stored in the local tarballs dir!
# cset_or_ref can be a branch or tag, if specified as 'ref=name'
# In this case, 'git ls-remote' is used to get the sha1 and can also
# be used to get a list valid refs (e.g. HEAD, refs/heads/master, refs/tags/v3.3.0)
# Usage: CT_GetGit <basename> <cset_or_ref> <url> <out_cset>
CT_GetGit() {
    local basename="${1}"
    local cset_or_ref="${2}"
    local url="${3}"
    local _out_cset="${4}"

    local ref=$(echo "${cset_or_ref}" | ${sed} -n 's/^ref=\(.*\)/\1/p')
    if [ -n "$ref" ]; then
        local matches=$(git ls-remote --exit-code "$url" --refs "${ref}")
        local result=$?
        CT_TestAndAbort "Failed to find git ref ${ref} at ${url}" "${result}" != "0"
        if [ $( echo "$matches" | wc -l) -gt 1 ]; then
            CT_DoLog WARN "Ambiguous ref ${ref} at ${url}, using first"
        fi
        local cset=$(echo "$matches" | head -n1 | cut -c1-6)
        CT_DoLog INFO "ref ${ref} at ${url} has cset of ${cset}"
    else
        local cset=${cset_or_ref}
        CT_DoLog INFO "cset ${cset}"
    fi

    if [ -n "${_out_cset}" ]; then
        eval ${_out_cset}=\${cset}
    fi

    local dir="${CT_TARBALLS_DIR}/${basename}-${cset}.git"
    local file="${basename}-${cset}.tar.gz"
    local dest="${CT_TARBALLS_DIR}/${file}"
    local tmp="${CT_TARBALLS_DIR}/${file}.tmp-dl"

    # Do we already have it?
    if CT_GetLocal "${file}"; then
        echo ${cset}
        return 0
    fi
    # Nope...

    if [ "${CT_FORBID_DOWNLOAD}" = "y" ]; then
        CT_DoLog WARN "Downloads forbidden, not trying git retrieval"
        return 1
    fi

    # Add URLs on the LAN mirror
    # We subvert the normal download method, just to look for
    # looking at the local mirror
    if CT_GetFile "${basename}-${cset}" .tar.gz; then
        return 0
    fi

    CT_DoLog EXTRA "Retrieving '${basename}-${cset}' (git)"

    # Remove potential left-over from a previous run
    CT_DoExecLog ALL rm -rf "${tmp}.tar.gz" "${tmp}.tar" "${tmp}" "${dir}"

    if CT_DoExecLog ALL git clone "${url}" "${dir}"; then
        # Yep, cloned OK
        CT_Pushd "${dir}"
        CT_DoExecLog ALL git archive --format=tar                       \
                                     --prefix="${basename}-${cset}/"    \
                                     -o "${tmp}.tar"                    \
                                     "${cset}"
        CT_DoExecLog ALL gzip -9 "${tmp}.tar"
        CT_DoExecLog ALL mv -f "${tmp}.tar.gz" "${dest}"
        CT_SaveLocal "${dest}"
        CT_DoExecLog ALL rm -rf "${tmp}.tar.gz" "${tmp}.tar" "${tmp}" "${dir}"
        CT_Popd
        echo ${cset}
        return 0
    else
        # Woops...
        CT_DoExecLog ALL rm -rf "${dir}"
        CT_DoLog Debug "Could not clone '${basename}'"
        return 1
    fi
}

# Extract a tarball
# Some tarballs need to be extracted in specific places. Eg.: glibc addons
# must be extracted in the glibc directory; uCLibc locales must be extracted
# in the extra/locale sub-directory of uClibc. This is taken into account
# by the caller, that did a 'cd' into the correct path before calling us
# and sets nochdir to 'nochdir'.
# Note also that this function handles the git trees!
# Usage: CT_Extract [nochdir] <basename> [options]
# where 'options' are dependent on the source (eg. git branch/tag...)
CT_Extract() {
    local nochdir="$1"
    local basename
    local ext
    local lzma_prog
    local -a tar_opts

    if [ "${nochdir}" = "nochdir" ]; then
        shift
        nochdir="$(pwd)"
    else
        nochdir="${CT_SRC_DIR}"
    fi

    basename="$1"
    shift

    # Check if already extracted
    if [ -e "${CT_SRC_DIR}/.${basename}.extracted" ]; then
        CT_DoLog DEBUG "Already extracted '${basename}'"
        return 0
    fi

    if ! ext="$(CT_GetFileExtension "${basename}")"; then
	CT_DoLog WARN "'${basename}' not found in '${CT_TARBALLS_DIR}'"
	return 1
    fi
    local full_file="${CT_TARBALLS_DIR}/${basename}${ext}"

    # Check if previously partially extracted
    if [ -e "${CT_SRC_DIR}/.${basename}.extracting" ]; then
        CT_DoLog ERROR "The '${basename}' sources were partially extracted."
        CT_DoLog ERROR "Please remove first:"
        CT_DoLog ERROR " - the source dir for '${basename}', in '${CT_SRC_DIR}'"
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${basename}.extracting'"
        CT_Abort "I'll stop now to avoid any carnage..."
    fi
    CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracting"

    CT_Pushd "${nochdir}"

    CT_DoLog EXTRA "Extracting '${basename}'"
    CT_DoExecLog FILE mkdir -p "${basename}"
    tar_opts=( "--strip-components=1" )
    tar_opts+=( "-C" "${basename}" )
    tar_opts+=( "-xv" )

    # One note here:
    # - lzma can be handled either with 'xz' or 'lzma'
    # - we get lzma tarball only if either or both are available
    # - so, if we get an lzma tarball, and either 'xz' or 'lzma' is
    #   missing, we can assume the other is available
    if [ "${CT_CONFIGURE_has_lzma}" = "y" ]; then
        lzma_prog="lzma -fdc"
    else
        lzma_prog="xz -fdc"
    fi
    case "${ext}" in
        .tar.xz)      xz -fdc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
        .tar.lzma)    ${lzma_prog} "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
        .tar.bz2)     bzip2 -dc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
        .tar.gz|.tgz) gzip -dc "${full_file}" | CT_DoExecLog FILE tar "${tar_opts[@]}" -f -;;
        .tar)         CT_DoExecLog FILE tar "${tar_opts[@]}" -f "${full_file}";;
        .zip)         CT_DoExecLog FILE unzip "${@}" "${full_file}";;
        /.git)        CT_ExtractGit "${basename}" "${@}";;
        *)            CT_DoLog WARN "Don't know how to handle '${basename}${ext}': unknown extension"
                      return 1
                      ;;
    esac

    # Don't mark as being extracted for git
    case "${ext}" in
        /.git)  ;;
        *)      CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${basename}.extracted";;
    esac
    CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${basename}.extracting"

    CT_Popd
}

# Create a working git clone of a local git repository
# Usage: CT_ExtractGit <basename> [ref]
# where 'ref' is the reference to use:
#   the full name of a branch, like "remotes/origin/branch_name"
#   a date as understandable by git, like "YYYY-MM-DD[ hh[:mm[:ss]]]"
#   a tag name
# If 'ref' is not given, the current repository HEAD will be used
CT_ExtractGit() {
    local basename="${1}"
    local ref="${2}"
    local repo
    local ref_type

    # pushd now to be able to get git revlist in case ref is a date
    repo="${CT_TARBALLS_DIR}/${basename}"
    CT_Pushd "${repo}"

    # What kind of reference is ${ref} ?
    if [ -z "${ref}" ]; then
        ref_type=head
        ref=$(git rev-list -n1 HEAD)
    elif git tag |${grep} -E "^${ref}$" >/dev/null 2>&1; then
        ref_type=tag
    elif git branch -a --no-color |${grep} -E "^. ${ref}$" >/dev/null 2>&1; then
        ref_type=branch
    elif date -d "${ref}" >/dev/null 2>&1; then
        ref_type=date
        ref=$(git rev-list -n1 --before="${ref}")
    else
        CT_Abort "Reference '${ref}' is an incorrect git reference: neither tag, branch nor date"
    fi

    CT_Popd

    CT_DoExecLog FILE rmdir "${basename}"
    case "${ref_type}" in
        branch) CT_DoExecLog FILE git clone -b "${ref}" "${repo}" "${basename}" ;;
        *)      CT_DoExecLog FILE git clone "${repo}" "${basename}"
                CT_Pushd "${basename}"
                CT_DoExecLog FILE git checkout "${ref}"
                CT_Popd
                ;;
    esac
}

# Patches the specified component
# See CT_Extract, above, for explanations on 'nochdir'
# Usage: CT_Patch [nochdir] <packagename> <packageversion>
# If the package directory is *not* packagename-packageversion, then
# the caller must cd into the proper directory first, and call us
# with nochdir
CT_Patch() {
    local nochdir="$1"
    local pkgname
    local version
    local pkgdir
    local base_file
    local ver_file
    local d
    local -a patch_dirs
    local bundled_patch_dir
    local local_patch_dir
    local bundled_exp_patch_dir
    local local_exp_patch_dir

    if [ "${nochdir}" = "nochdir" ]; then
        shift
        pkgname="$1"
        version="$2"
        pkgdir="${pkgname}-${version}"
        nochdir="$(pwd)"
    else
        pkgname="$1"
        version="$2"
        pkgdir="${pkgname}-${version}"
        nochdir="${CT_SRC_DIR}/${pkgdir}"
    fi

    # Check if already patched
    if [ -e "${CT_SRC_DIR}/.${pkgdir}.patched" ]; then
        CT_DoLog DEBUG "Already patched '${pkgdir}'"
        return 0
    fi

    # Check if already partially patched
    if [ -e "${CT_SRC_DIR}/.${pkgdir}.patching" ]; then
        CT_DoLog ERROR "The '${pkgdir}' sources were partially patched."
        CT_DoLog ERROR "Please remove first:"
        CT_DoLog ERROR " - the source dir for '${pkgdir}', in '${CT_SRC_DIR}'"
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.extracted'"
        CT_DoLog ERROR " - the file '${CT_SRC_DIR}/.${pkgdir}.patching'"
        CT_Abort "I'll stop now to avoid any carnage..."
    fi
    touch "${CT_SRC_DIR}/.${pkgdir}.patching"

    CT_Pushd "${nochdir}"

    CT_DoLog EXTRA "Patching '${pkgdir}'"

    bundled_patch_dir="${CT_LIB_DIR}/patches/${pkgname}/${version}"
    bundled_patch_arch_dir="${bundled_patch_dir}/${CT_ARCH}"
    local_patch_dir="${CT_LOCAL_PATCH_DIR}/${pkgname}/${version}"

    case "${CT_PATCH_ORDER}" in
        bundled)        patch_dirs=("${bundled_patch_dir}" "${bundled_patch_arch_dir}");;
        local)          patch_dirs=("${local_patch_dir}");;
        bundled,local)  patch_dirs=("${bundled_patch_dir}" "${bundled_patch_arch_dir}" "${local_patch_dir}");;
        local,bundled)  patch_dirs=("${local_patch_dir}" "${bundled_patch_dir}" "${bundled_patch_arch_dir}");;
        none)           patch_dirs=;;
    esac

    for d in "${patch_dirs[@]}"; do
        CT_DoLog DEBUG "Looking for patches in '${d}'..."
        if [ -n "${d}" -a -d "${d}" ]; then
            for p in "${d}"/*.patch; do
                if [ -f "${p}" ]; then
                    CT_DoExecLog ALL ${patch} --no-backup-if-mismatch -g0 -F1 -p1 -f -i "${p}"
                fi
            done
            if [ "${CT_PATCH_SINGLE}" = "y" ]; then
                break
            fi
        fi
    done

    if [ "${CT_OVERIDE_CONFIG_GUESS_SUB}" = "y" ]; then
        CT_DoLog ALL "Overiding config.guess and config.sub"
        for cfg in config_guess config_sub; do
            eval ${cfg}="${CT_LIB_DIR}/scripts/${cfg/_/.}"
            [ -e "${CT_TOP_DIR}/scripts/${cfg/_/.}" ] && eval ${cfg}="${CT_TOP_DIR}/scripts/${cfg/_/.}"
            # Can't use CT_DoExecLog because of the '{} \;' to be passed un-mangled to find
            find . -type f -name "${cfg/_/.}" \
                -exec chmod -v u+w {} \; \
                -exec cp -v "${!cfg}" {} \; |CT_DoLog ALL
        done
    fi

    CT_DoExecLog DEBUG touch "${CT_SRC_DIR}/.${pkgdir}.patched"
    CT_DoExecLog DEBUG rm -f "${CT_SRC_DIR}/.${pkgdir}.patching"

    CT_Popd
}

# Two wrappers to call config.(guess|sub) either from CT_TOP_DIR or CT_LIB_DIR.
# Those from CT_TOP_DIR, if they exist, will be be more recent than those from CT_LIB_DIR.
CT_DoConfigGuess() {
    if [ -x "${CT_TOP_DIR}/scripts/config.guess" ]; then
        "${CT_TOP_DIR}/scripts/config.guess"
    else
        "${CT_LIB_DIR}/scripts/config.guess"
    fi
}

CT_DoConfigSub() {
    if [ -x "${CT_TOP_DIR}/scripts/config.sub" ]; then
        "${CT_TOP_DIR}/scripts/config.sub" "$@"
    else
        "${CT_LIB_DIR}/scripts/config.sub" "$@"
    fi
}

# Normally, each step is executed in a sub-shell and thus cannot modify the
# environment for the next step(s). When this is needed, it can do so by
# invoking this function.
# Usage: CT_EnvModify VAR VALUE
CT_EnvModify() {
    echo "${1}=\"${2}\"" >> "${CT_BUILD_DIR}/env.modify.sh"
}

# Compute the target tuple from what is provided by the user
# Usage: CT_DoBuildTargetTuple
# In fact this function takes the environment variables to build the target
# tuple. It is needed both by the normal build sequence, as well as the
# sample saving sequence.
CT_DoBuildTargetTuple() {
    # Set the endianness suffix, and the default endianness gcc option
    case "${CT_ARCH_ENDIAN}" in
        big)
            target_endian_eb=eb
            target_endian_be=be
            target_endian_el=
            target_endian_le=
            CT_ARCH_ENDIAN_CFLAG="-mbig-endian"
            CT_ARCH_ENDIAN_LDFLAG="-Wl,-EB"
            ;;
        little)
            target_endian_eb=
            target_endian_be=
            target_endian_el=el
            target_endian_le=le
            CT_ARCH_ENDIAN_CFLAG="-mlittle-endian"
            CT_ARCH_ENDIAN_LDFLAG="-Wl,-EL"
            ;;
    esac

    # Set the bitness suffix
    case "${CT_ARCH_BITNESS}" in
        32)
            target_bits_32=32
            target_bits_64=
            ;;
        64)
            target_bits_32=
            target_bits_64=64
            ;;
    esac

    # Build the default architecture tuple part
    CT_TARGET_ARCH="${CT_ARCH}${CT_ARCH_SUFFIX}"

    # Set defaults for the system part of the tuple. Can be overriden
    # by architecture-specific values.
    case "${CT_LIBC}" in
        *glibc) CT_TARGET_SYS=gnu;;
        uClibc) CT_TARGET_SYS=uclibc;;
        musl)   CT_TARGET_SYS=musl;;
        avr-libc)
            # avr-libc only seems to work with the non-canonical "avr" target.
            CT_TARGET_SKIP_CONFIG_SUB=y
            CT_TARGET_SYS= # CT_TARGET_SYS must be empty too
        ;;
        *)      CT_TARGET_SYS=elf;;
    esac

    # Set the default values for ARCH, ABI, CPU, TUNE, FPU and FLOAT
    unset CT_ARCH_ARCH_CFLAG CT_ARCH_ABI_CFLAG CT_ARCH_CPU_CFLAG CT_ARCH_TUNE_CFLAG CT_ARCH_FPU_CFLAG CT_ARCH_FLOAT_CFLAG
    unset CT_ARCH_WITH_ARCH CT_ARCH_WITH_ABI CT_ARCH_WITH_CPU CT_ARCH_WITH_TUNE CT_ARCH_WITH_FPU CT_ARCH_WITH_FLOAT
    [ "${CT_ARCH_ARCH}"     ] && { CT_ARCH_ARCH_CFLAG="-march=${CT_ARCH_ARCH}";  CT_ARCH_WITH_ARCH="--with-arch=${CT_ARCH_ARCH}"; }
    [ "${CT_ARCH_ABI}"      ] && { CT_ARCH_ABI_CFLAG="-mabi=${CT_ARCH_ABI}";     CT_ARCH_WITH_ABI="--with-abi=${CT_ARCH_ABI}";    }
    [ "${CT_ARCH_CPU}"      ] && { CT_ARCH_CPU_CFLAG="-mcpu=${CT_ARCH_CPU}";     CT_ARCH_WITH_CPU="--with-cpu=${CT_ARCH_CPU}";    }
    [ "${CT_ARCH_TUNE}"     ] && { CT_ARCH_TUNE_CFLAG="-mtune=${CT_ARCH_TUNE}";  CT_ARCH_WITH_TUNE="--with-tune=${CT_ARCH_TUNE}"; }
    [ "${CT_ARCH_FPU}"      ] && { CT_ARCH_FPU_CFLAG="-mfpu=${CT_ARCH_FPU}";     CT_ARCH_WITH_FPU="--with-fpu=${CT_ARCH_FPU}";    }

    case "${CT_ARCH_FLOAT}" in
        hard)
            CT_ARCH_FLOAT_CFLAG="-mhard-float"
            CT_ARCH_WITH_FLOAT="--with-float=hard"
            ;;
        soft)
            CT_ARCH_FLOAT_CFLAG="-msoft-float"
            CT_ARCH_WITH_FLOAT="--with-float=soft"
            ;;
        softfp)
            CT_ARCH_FLOAT_CFLAG="-mfloat-abi=softfp"
            CT_ARCH_WITH_FLOAT="--with-float=softfp"
            ;;
    esac

    # Build the default kernel tuple part
    CT_TARGET_KERNEL="${CT_KERNEL}"

    # Overide the default values with the components specific settings
    CT_DoArchTupleValues
    CT_DoKernelTupleValues

    # Finish the target tuple construction
    CT_TARGET="${CT_TARGET_ARCH}"
    CT_TARGET="${CT_TARGET}${CT_TARGET_VENDOR:+-${CT_TARGET_VENDOR}}"
    CT_TARGET="${CT_TARGET}${CT_TARGET_KERNEL:+-${CT_TARGET_KERNEL}}"
    CT_TARGET="${CT_TARGET}${CT_TARGET_SYS:+-${CT_TARGET_SYS}}"

    # Sanity checks
    __sed_alias=""
    if [ -n "${CT_TARGET_ALIAS_SED_EXPR}" ]; then
        __sed_alias=$(echo "${CT_TARGET}" |${sed} -r -e "${CT_TARGET_ALIAS_SED_EXPR}")
    fi
    case ":${CT_TARGET_VENDOR}:${CT_TARGET_ALIAS}:${__sed_alias}:" in
      :*" "*:*:*:) CT_Abort "Don't use spaces in the vendor string, it breaks things.";;
      :*"-"*:*:*:) CT_Abort "Don't use dashes in the vendor string, it breaks things.";;
      :*:*" "*:*:) CT_Abort "Don't use spaces in the target alias, it breaks things.";;
      :*:*:*" "*:) CT_Abort "Don't use spaces in the target sed transform, it breaks things.";;
    esac

    # Canonicalise it
    if [ "${CT_TARGET_SKIP_CONFIG_SUB}" != "y" ]; then
        CT_TARGET=$(CT_DoConfigSub "${CT_TARGET}")
    fi

    # Prepare the target CFLAGS
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ENDIAN_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ARCH_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_ABI_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_CPU_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_TUNE_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FPU_CFLAG}"
    CT_ARCH_TARGET_CFLAGS="${CT_ARCH_TARGET_CFLAGS} ${CT_ARCH_FLOAT_CFLAG}"

    # Now on for the target LDFLAGS
    CT_ARCH_TARGET_LDFLAGS="${CT_ARCH_TARGET_LDFLAGS} ${CT_ARCH_ENDIAN_LDFLAG}"

    # Now, a multilib quirk. We may not be able to pass CT_ARCH_TARGET_CFLAGS
    # and CT_ARCH_TARGET_LDFLAGS to gcc: even though GCC build appends the multilib
    # flags afterwards, on some architectures the build breaks because some
    # flags do not completely override each other. For example, on mips target,
    # 'gcc -mabi=32' and 'gcc -mabi=n32' both work, but 'gcc -mabi=32 -mabi=n32'
    # triggers an internal linker error. Likely a bug in GNU binutils, but we
    # have to work it around for now: *do not pass the CT_ARCH_TARGET_ flags*.
    # Instead, save them into a different variable here. Then, after the first
    # core pass, we'll know which of them vary with multilibs (i.e. must be
    # filtered out).
    if [ "${CT_MULTILIB}" = "y" ]; then
        CT_ARCH_TARGET_CFLAGS_MULTILIB="${CT_ARCH_TARGET_CFLAGS}"
        CT_ARCH_TARGET_CFLAGS=
        CT_ARCH_TARGET_LDFLAGS_MULTILIB="${CT_ARCH_TARGET_LDFLAGS}"
        CT_ARCH_TARGET_LDFLAGS=
    fi
}

# This function determines the target tuple for a given set of compiler
# flags, using either GCC's multiarch feature (if supported; if not,
# GCC prints nothing and exits with status 0), falling back to calling
# the architecture-specific functions.
CT_DoMultilibTarget() {
    local target="$1"; shift
    local -a multi_flags=( "$@" )
    local gcc_multiarch

    gcc_multiarch=$( "${CT_TARGET}-gcc" -print-multiarch "${multi_flags[@]}" )
    if [ -n "${gcc_multiarch}" ]; then
        echo "${gcc_multiarch}"
        return
    fi

    # Fall back to arch-specific guesswork
    CT_DoArchMultilibTarget "${target}" "${multi_flags[@]}"
}

# This function does pause the build until the user strikes "Return"
# Usage: CT_DoPause [optional_message]
CT_DoPause() {
    local foo
    local message="${1:-Pausing for your pleasure}"
    CT_DoLog INFO "${message}"
    read -p "Press 'Enter' to continue, or Ctrl-C to stop..." foo >&6
    return 0
}

# This function creates a tarball of the specified directory, but
# only if it exists
# Usage: CT_DoTarballIfExists <dir> <tarball_basename> [extra_tar_options [...]]
CT_DoTarballIfExists() {
    local dir="$1"
    local tarball="$2"
    shift 2
    local -a extra_tar_opts=( "$@" )
    local -a compress

    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
        y)  compress=( gzip -c -3 - ); tar_ext=.gz;;
        *)  compress=( cat - );        tar_ext=;;
    esac

    if [ -d "${dir}" ]; then
        CT_DoLog DEBUG "  Saving '${dir}'"
        { tar c -C "${dir}" -v -f - "${extra_tar_opts[@]}" .    \
          |"${compress[@]}" >"${tarball}.tar${tar_ext}"         ;
        } 2>&1 |${sed} -r -e 's/^/    /;' |CT_DoLog STATE
    else
        CT_DoLog STATE "  Not saving '${dir}': does not exist"
    fi
}

# This function extracts a tarball to the specified directory, but
# only if the tarball exists
# Usage: CT_DoExtractTarballIfExists <tarball_basename> <dir> [extra_tar_options [...]]
CT_DoExtractTarballIfExists() {
    local tarball="$1"
    local dir="$2"
    shift 2
    local -a extra_tar_opts=( "$@" )
    local -a uncompress

    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
        y)  uncompress=( gzip -c -d ); tar_ext=.gz;;
        *)  uncompress=( cat );        tar_ext=;;
    esac

    if [ -f "${tarball}.tar${tar_ext}" ]; then
        CT_DoLog DEBUG "  Restoring '${dir}'"
        CT_DoForceRmdir "${dir}"
        CT_DoExecLog DEBUG mkdir -p "${dir}"
        { "${uncompress[@]}" "${tarball}.tar${tar_ext}"     \
          |tar x -C "${dir}" -v -f - "${extra_tar_opts[@]}" ;
        } 2>&1 |${sed} -r -e 's/^/    /;' |CT_DoLog STATE
    else
        CT_DoLog STATE "  Not restoring '${dir}': does not exist"
    fi
}

# This function saves the state of the toolchain to be able to restart
# at any one point
# Usage: CT_DoSaveState <next_step_name>
CT_DoSaveState() {
	[ "${CT_DEBUG_CT_SAVE_STEPS}" = "y" ] || return 0
    local state_name="$1"
    local state_dir="${CT_STATE_DIR}/${state_name}"

    CT_DoLog INFO "Saving state to restart at step '${state_name}'..."

    rm -rf "${state_dir}"
    mkdir -p "${state_dir}"

    CT_DoLog STATE "  Saving environment and aliases"
    # We must omit shell functions, and some specific bash variables
    # that break when restoring the environment, later. We could do
    # all the processing in the awk script, but a sed is easier...
    set |${awk} '
              BEGIN { _p = 1; }
              $0~/^[^ ]+ \(\)/ { _p = 0; }
              _p == 1
              $0 == "}" { _p = 1; }
              ' |${sed} -r -e '/^BASH_(ARGC|ARGV|LINENO|SOURCE|VERSINFO)=/d;
                           /^(UID|EUID)=/d;
                           /^(FUNCNAME|GROUPS|PPID|SHELLOPTS)=/d;' >"${state_dir}/env.sh"

    CT_DoTarballIfExists "${CT_BUILDTOOLS_PREFIX_DIR}" "${state_dir}/buildtools_dir"
    CT_DoTarballIfExists "${CT_CONFIG_DIR}" "${state_dir}/config_dir"
    CT_DoTarballIfExists "${CT_PREFIX_DIR}" "${state_dir}/prefix_dir" --exclude '*.log'

    CT_DoLog STATE "  Saving log file"
    exec >/dev/null
    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
        y)  gzip -3 -c "${tmp_log_file}"  >"${state_dir}/log.gz";;
        *)  cat "${tmp_log_file}" >"${state_dir}/log";;
    esac
    exec >>"${tmp_log_file}"
}

# This function restores a previously saved state
# Usage: CT_DoLoadState <state_name>
CT_DoLoadState(){
    local state_name="$1"
    local state_dir="${CT_STATE_DIR}/${state_name}"
    local old_RESTART="${CT_RESTART}"
    local old_STOP="${CT_STOP}"

    CT_TestOrAbort "The previous build did not reach the point where it could be restarted at '${CT_RESTART}'" -d "${state_dir}"

    # We need to do something special with the log file!
    if [ "${CT_LOG_TO_FILE}" = "y" ]; then
        exec >"${state_dir}/tail.log"
    fi

    CT_DoLog INFO "Restoring state at step '${state_name}', as requested."

    CT_DoExtractTarballIfExists "${state_dir}/prefix_dir" "${CT_PREFIX_DIR}"
    CT_DoExtractTarballIfExists "${state_dir}/config_dir" "${CT_CONFIG_DIR}"
    CT_DoExtractTarballIfExists "${state_dir}/buildtools_dir" "${CT_BUILDTOOLS_PREFIX_DIR}"

    # Restore the environment, discarding any error message
    # (for example, read-only bash internals)
    CT_DoLog STATE "  Restoring environment"
    . "${state_dir}/env.sh" >/dev/null 2>&1 || true

    # Restore the new RESTART and STOP steps
    CT_RESTART="${old_RESTART}"
    CT_STOP="${old_STOP}"
    unset old_stop old_restart

    CT_DoLog STATE "  Restoring log file"
    exec >/dev/null
    case "${CT_DEBUG_CT_SAVE_STEPS_GZIP}" in
        y)  gzip -dc "${state_dir}/log.gz" >"${tmp_log_file}";;
        *)  cat "${state_dir}/log" >"${tmp_log_file}";;
    esac
    cat "${state_dir}/tail.log" >>"${tmp_log_file}"
    exec >>"${tmp_log_file}"
    rm -f "${state_dir}/tail.log"
}

# This function sets a kconfig option to a specific value in a .config file
# Usage: CT_KconfigSetOption <option> <value> <file>
CT_KconfigSetOption() {
    option="$1"
    value="$2"
    file="$3"

    ${grep} -E -q "^${option}=.*" "${file}" && \
        ${sed} -i -r -e "s;^${option}=.*$;${option}=${value};" "${file}" || \
    ${grep} -E -q "^# ${option} is not set$" "${file}" && \
        ${sed} -i -r -e "s;^# ${option} is not set$;${option}=${value};" "${file}" || \
    echo "${option}=${value}" >> "${file}"
}

# This function enables a kconfig option to '=y' in a .config file
# Usage: CT_KconfigEnableOption <option> <file>
CT_KconfigEnableOption() {
    option="$1"
    file="$2"

    CT_KconfigSetOption "${option}" "y" "${file}"
}

# This function disables a kconfig option in a .config file
# Usage: CT_KconfigDisableOption <option> <file>
CT_KconfigDisableOption() {
    option="${1}"
    file="${2}"

    ${grep} -E -q "^# ${option} is not set$" "${file}" || \
    ${grep} -E -q "^${option}=.*$" "${file}" && \
        ${sed} -i -r -e "s;^${option}=.*$;# ${option} is not set;" "${file}" || \
    echo "# ${option} is not set" >> "${file}"
}

# This function deletes a kconfig option in a .config file, no matter if it
# is set or commented out.
# Usage: CT_KconfigDeleteOption <option> <file>
CT_KconfigDeleteOption() {
    option="${1}"
    file="${2}"

    ${grep} -E -q "^# ${option} is not set$" "${file}" && \
        ${sed} -i -r -e "/^# ${option} is not set$/d" "${file}" || \
    ${grep} -E -q "^${option}=.*$" "${file}" && \
        ${sed} -i -r -e "/^${option}=.*$/d" "${file}" || true
}