File: drbl-functions

package info (click to toggle)
drbl 5.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,996 kB
  • sloc: sh: 43,555; perl: 8,820; xml: 867; makefile: 135
file content (5331 lines) | stat: -rwxr-xr-x 224,880 bytes parent folder | download
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
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
#!/bin/bash
# -*-Shell-script-*-
# Steven Shiau <steven _at_ clonezilla org>
# Ceasar Sun <ceasar dot sun _at_ gmail com>
# License: GPL
#
# Functions:	This file contains functions to be used by most or all	shell scripts in the DRBL environment
#
# //NOTE// Do NOT set the locale by "export LC_ALL=C". It will make dialog distortation.

# Source DRBL setting
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. /etc/drbl/drbl.conf

# Append a default search path.
# To make it like: 
# PATH="$PATH:$DRBL_SCRIPT_PATH/sbin:$DRBL_SCRIPT_PATH/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin"
path_to_add="$DRBL_SCRIPT_PATH/sbin $DRBL_SCRIPT_PATH/bin /usr/sbin /usr/bin /sbin"
for i in $path_to_add; do
  if [ -z "$(echo $PATH | grep -Fw $i)" ]; then
    PATH="$PATH:$i"
  fi
done
export PATH

# setup some parameters for color output. The variables should be already 
# defined in the /etc/init.d/functions in RH-like distribution 

# Check if terminal supports colors output
colors_no="$(LC_ALL=C tput colors 2>/dev/null)"

BOOTUP=""
if [ -n "$colors_no" ]; then
  if [ "$colors_no" -ge 8 ]; then
    [ -z "$SETCOLOR_SUCCESS" ] && SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    [ -z "$SETCOLOR_FAILURE" ] && SETCOLOR_FAILURE="echo -en \\033[1;31m"
    [ -z "$SETCOLOR_WARNING" ] && SETCOLOR_WARNING="echo -en \\033[1;33m"
    [ -z "$SETCOLOR_NORMAL"  ] && SETCOLOR_NORMAL="echo -en \\033[0;39m"
    BOOTUP="color"
  fi
fi

# some functions
# get OS type
get_os_type() {
  case "$OS_Version" in
     RH*|FC*|CO*)
        OS_type="RH"
        ;;
     MD[KV]*)
        OS_type="MDK"
        ;;
     DBN*)
        OS_type="DBN"
        ;;
     SUSE*)
        OS_type="SUSE"
        ;;
     *)
        echo "This version in this distribution is NOT supported by DRBL, maybe you can try to use the drbl in testing or unstable repository. Program terminated!"
        exit 1 
  esac
} # end of get OS type

#
check_distribution_name() {
  local VER
  local DIST
  local FULL_DIST
  # Reset these values
  OS_Version=
  FULL_OS_Version=
  # FULL_OS_Version is only used in the label
  # like the files /tftpboot/nbi_img/pxelinux.cfg/* (default or 0A....).
  # OS_Version is used in drblsrv and drblpush to judge the dist and version.
  if [ -f /etc/fedora-release ]; then
   VER=$(rpm -qf /etc/fedora-release --qf "%{VERSION}" | sed "s/[^0-9\.]//g")
   DIST=FC
   FULL_DIST=Fedora
  elif [ -f /etc/mandriva-release ]; then
   VER=$(rpm -qf /etc/mandriva-release --qf "%{VERSION}" | sed "s/[^0-9\.]//g")
   DIST=MDV
   FULL_DIST=Mandriva
  elif [ -f /etc/mandrake-release ]; then
   # /etc/mandrake-release must be after the /etc/mandriva-release, since the
   # new Mandriva distributions has /etc/mandrake-release, too.
   VER=$(rpm -qf /etc/mandrake-release --qf "%{VERSION}" | sed "s/[^0-9\.]//g")
   if [ "$VER" = "10.2" ]; then
     # Exception:
     # "Mandrakelinux release 10.2.*" /etc/mandrakelinux-release
     # OS_Version="MDV2005"
     DIST=MDV
     FULL_DIST=Mandriva
     VER=2005
   else
     DIST=MDK
     FULL_DIST=Mandrake
   fi
  elif [ -e /etc/SuSE-release ]; then
   VER=$(rpm -qf /etc/SuSE-release --qf "%{VERSION}" | sed "s/[^0-9\.]//g")
   DIST=SUSE
   FULL_DIST=SuSE
  elif [ -f /etc/redhat-release ]; then
   # /etc/redhat-release must be the last "elif" for RH-like dist, since there
   # are so many distributions are based on RH, and do exist /etc/redhat-release
   if grep -q -i "CentOS" /etc/redhat-release; then
     # The release of CentOS is a little difference, we can not use
     # rpm -qf /etc/redhat-release --qf "%{VERSION}" to get the version, since
     # we will get "4", but actually it's "4.2" or "4.1"
     VER=$(cat /etc/redhat-release | sed "s/[^0-9\.]//g")
     DIST=CO
     FULL_DIST=CentOS
   elif grep -q -i "Scientific Linux" /etc/redhat-release; then
     # Scientific Linux
     # To simplify that, we only support drblsrv-offline for Scientific Linux
     # The DIST is set as CO for compatibility.
     VER=$(cat /etc/redhat-release | sed "s/[^0-9\.]//g")
     DIST=CO
     FULL_DIST=SL
   elif grep -q -i "OSSII" /etc/redhat-release; then
     # The release of OSSII M6 Linux is like:
     # OSSII M6 Linux
     # To simplify that, we only support drblsrv-offline for OSSII
     # The DIST is set as CO for compatibility, basically it's useless here.
     VER=$(grep -Eo "M[[:digit:]]" /etc/redhat-release)
     DIST=CO
     FULL_DIST=OSSII
   else
     # The last one... RedHat
     # In some case, no idea why, when run this as root in RH9, it will crash
     # [root]# rpm -qf --qf '%{VERSION}' /etc/redhat-release
     # Segmentation fault
     # So we do not use this:
     #VER=$(rpm -qf /etc/redhat-release --qf "%{VERSION}" | sed "s/[^0-9\.]//g")
     # We use this:
     VER=$(cat /etc/redhat-release | sed "s/[^0-9\.]//g")
     DIST=RH
     FULL_DIST=RedHat
   fi
  elif [ -f /etc/debian_version ]; then
   DIST=DBN
   FULL_DIST=Debian
   # get the version
   if grep -qE "(testing/unstable|sid)" /etc/debian_version; then
     VER="-TU"
     # Here we assign a better tag for FULL_OS_Version
     FULL_OS_Version="Debian Testing-Unstable"
   else
     VER="$(cat /etc/debian_version)"
   fi
   # Overwrite the FULL_OS_Version if others are found. Especially for Ubuntu
   if [ -e /etc/lsb-release ]; then
     . /etc/lsb-release
     FULL_OS_Version="$DISTRIB_ID $DISTRIB_RELEASE"
   fi
  fi

  if [ -z "$DIST" -o -z "$VER" ]; then
    echo "The distribution or version is unknown! Program terminated!"
    exit 1
  fi
  # If not assigned, assign it
  [ -z "$OS_Version" ] && OS_Version="${DIST}${VER}"
  [ -z "$OS_DIST" ] && OS_DIST="${DIST}"
  [ -z "$FULL_OS_Version" ] && FULL_OS_Version="${FULL_DIST} ${VER}"

  # get the OS_type variable
  get_os_type
  #
  # echo $OS_Version
} # end of check_distribution_name

# create the shared library program runtime env.
# ldd might give these 3 type results:
# 1. newer version (FC3):
# ldd /sbin/depmod
#         libc.so.6 => /lib/libc.so.6 (0x00a08000)
#         /lib/ld-linux.so.2 (0x009f1000)
# 2. older version (RH8/9,FC1/2):
# ldd /sbin/depmod
#         libc.so.6 => /lib/libc.so.6 (0x40025000)
#         /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
# 3. MDK10
#         linux-gate.so.1 =>  (0xffffe000)
#         libc.so.6 => /lib/tls/libc.so.6 (0x40028000)
#         /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
#RH9:
#libc.so.6 => /lib/libc.so.6 (0x40025000)
#/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
#FC1:
#libc.so.6 => /lib/libc.so.6 (0x00a35000)
#/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00a20000)
#FC2:
#libc.so.6 => /lib/libc.so.6 (0x00b76000)
#linux.so.2 => /lib/ld-linux.so.2 (0x00b61000)
#FC3:
#libc.so.6 => /lib/tls/i686/libc.so.6 (0x007b3000)
#linux.so.2 (0x0079c000)
#mdk10:
#linux-gate.so.1 =>  (0xffffe000)
#libc.so.6 => /lib/tls/libc.so.6 (0x40028000)
#/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
 
create_depmod_env() {
  # This function is useless from drbl 1.7.6-23 or later, since we use 
  # depmod -b baseroot/ instead of chroot.
  # However, we still keep this for ref.
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  # some distribution, like Mandriva, use link in /sbin/depmod, so we clean it
  # to avoid some error.
  [ -e "$newroot/sbin/depmod" ] && rm -f $newroot/sbin/depmod
  # -L: always follow symbolic links
  cp -L --parents /sbin/depmod* $newroot
  export DESTDIR="$newroot"
  if ldd /sbin/depmod &>/dev/null; then
    depmod_lib_need=$(LC_ALL=C ldd /sbin/depmod | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
    for imod in $depmod_lib_need; do
      # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
      [ "$imod" = "linux-vdso.so.1" ] && continue
      [ "$imod" = "linux-gate.so.1" ] && continue
      #cp --parents -d $imod $newroot
      copy_exec_drbl $imod "$(LC_ALL=C dirname $imod)"
    done
  fi
}
clean_depmod_env() {
  # This function is useless from drbl 1.7.6-23 or later, since we use 
  # depmod -b baseroot/ instead of chroot.
  # However, we still keep this for ref.
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  [ -f $newroot/sbin/depmod ] && rm -f $newroot/sbin/depmod
  # for MDK 9.2, there is another depmod.old...
  [ -f $newroot/sbin/depmod.old ] && rm -f $newroot/sbin/depmod.old
  if ldd /sbin/depmod &>/dev/null; then
    depmod_lib_need=$(LC_ALL=C ldd /sbin/depmod | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
    for f2rm in $depmod_lib_need; do
      [ -f "$newroot/$f2rm" ] && rm -f $newroot/$f2rm
    done
  fi
}

# function to create chkconfig environment
create_chkconfig_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  cp --parents /sbin/chkconfig $newroot
  export DESTDIR="$newroot"
  if ldd /sbin/chkconfig &>/dev/null; then
    chkconfig_lib_need=$(LC_ALL=C ldd /sbin/chkconfig | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
    for imod in $chkconfig_lib_need; do
      # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
      [ "$imod" = "linux-vdso.so.1" ] && continue
      [ "$imod" = "linux-gate.so.1" ] && continue
      #cp --parents -d $imod $newroot
      copy_exec_drbl $imod "$(LC_ALL=C dirname $imod)"
    done
  fi
}

# function to clean chkconfig environment
clean_chkconfig_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  chkconfig_lib_need=$(LC_ALL=C ldd /sbin/chkconfig | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
  [ -f $newroot/sbin/chkconfig ] && rm -f $newroot/sbin/chkconfig
  for f2rm in $chkconfig_lib_need; do
    [ -f $newroot/$f2rm ] && rm -f $newroot/$f2rm
  done
}

# function to create insserv environment
create_insserv_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  cp --parents -d /sbin/insserv $newroot
  export DESTDIR="$newroot"
  if ldd /sbin/insserv &>/dev/null; then
    insserv_lib_need=$(LC_ALL=C ldd /sbin/insserv | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
    for imod in $insserv_lib_need; do
      # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
      [ "$imod" = "linux-vdso.so.1" ] && continue
      [ "$imod" = "linux-gate.so.1" ] && continue
      #cp --parents -d $imod $newroot
      copy_exec_drbl $imod "$(LC_ALL=C dirname $imod)"
    done
  fi
}
# Check if root or not
check_if_root() {
   if [ ! "$UID" = "0" ]; then
     echo
     echo "[$LOGNAME] You need to run this script \"`basename $0`\" as root."
     echo
     exit 1
   fi
}

# function to get the autologin_account
# input is the host dir, like /tftpboot/nodes/192.168.1.1, then
# return the auto_login ID
get_autologin_account() {
    local ihost="$1"
    local ip HOSTNAME
    # $auto_login_id and $echo_no_digit_0_1 are global variables
    # auto login username is set as hostname, i.e. use client's hostname as the auto-login ID.
    # Reset variable auto_login_id
    auto_login_id=""
    if [ -e /etc/debian_version ]; then
      # Debian
      auto_login_id="$(cat $ihost/etc/hostname 2>/dev/null)"
    elif [ -e /etc/SuSE-release ]; then
      # SuSE
      auto_login_id="$(cat $ihost/etc/HOSTNAME 2>/dev/null | sed -e "s/\..*//g")"
    else
      # RH-like
      if [ -e $ihost/$SYSCONF_PATH/network ]; then
        HOSTNAME=""
        . $ihost/$SYSCONF_PATH/network
        auto_login_id="$HOSTNAME"
      fi
    fi
    # if no hostname, such as in DRBL SSI mode, try to map the hostname from $IP_HOST_TABLE
    if [ -z "$auto_login_id" ]; then
      ip="$(basename $ihost)"
      auto_login_id="$(awk -F" " "/^$ip[[:space:]]+/ {print \$2}" $IP_HOST_TABLE)"
    fi

    # Added by Ceasar:
    # auto-login account can be defined via: /etc/drbl/auto_login_host_id_passwd.txt
    # Read /etc/drbl/auto_login_host_id_passwd.example as sample
    auto_login_host_id_passwd_file="/etc/drbl/auto_login_host_id_passwd.txt"
    _tmp_auto_login_id="$(LC_ALL=C awk  -v auto_login_id="$auto_login_id" '{if ($1 == auto_login_id ) {print $2}}' $auto_login_host_id_passwd_file 2>/dev/null )"
    _tmp_auto_login_passwd="$(LC_ALL=C awk -v auto_login_id="$auto_login_id"  '{if ($1 == auto_login_id ) {print $3}}' $auto_login_host_id_passwd_file 2>/dev/null )"

    if [ -n "$_tmp_auto_login_id" ] ; then
      auto_login_id="$_tmp_auto_login_id"
      password_opt="$_tmp_auto_login_passwd"
    fi 
}
# only show existing autologin account
get_existing_autologin_account() {
    local ihost="$1"
    get_autologin_account $ihost
    if grep -q $auto_login_id /etc/passwd ; then
      # account $auto_login_id exists, show it
      echo "$auto_login_id"
    fi
}

# check switch if it is input correct as on or off
check_switch_on_off() {
  local switch="$1"
  case "$switch" in
    on|ON|[oO]|[nN]|off|OFF|[oO][fF][fF])
         true;;
     "")
         usage && exit 1
         ;;
     *)
         echo "You must specify \"on\" or \"off\" !!! Program stop!!!"
         exit 1
         ;;
  esac
}

#
create_authconfig_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
   file_need="/usr/sbin/authconfig /usr/sbin/pwconv /usr/sbin/grpconv"
   cp --parents $file_need $newroot

   if ldd /usr/sbin/authconfig &>/dev/null; then
     authconfig_lib_need=$(LC_ALL=C ldd /usr/sbin/authconfig | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
     for imod in $authconfig_lib_need; do
       # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
       [ "$imod" = "linux-vdso.so.1" ] && continue
       [ "$imod" = "linux-gate.so.1" ] && continue
       cp --parents -d $imod $newroot
     done
   fi
   if ldd /usr/sbin/pwconf &>/dev/null; then
     pwconf_lib_need=$(LC_ALL=C ldd /usr/sbin/pwconf | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
     for imod in $pwconf_lib_need; do
       # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
       [ "$imod" = "linux-vdso.so.1" ] && continue
       [ "$imod" = "linux-gate.so.1" ] && continue
       cp --parents -d $imod $newroot
     done
   fi
   if ldd /usr/sbin/grpconv &>/dev/null; then
     grpconv_lib_need=$(LC_ALL=C ldd /usr/sbin/grpconv | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
     for imod in $grpconv_lib_need; do
       # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
       [ "$imod" = "linux-vdso.so.1" ] && continue
       [ "$imod" = "linux-gate.so.1" ] && continue
       cp --parents -d $imod $newroot
     done
   fi
}

#
create_chpasswd_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  # These *.so were found by using strace
  # If something goes wrong in newer GNU/Linux distribution, we can find more by:
  # (1) uncomment this line in this function:
  #     # cp --parents /usr/bin/strace $newroot
  # (2) in drbl-client-root-passwd, make it run
  #     echo "root:$new_passwd" | /usr/bin/strace /usr/sbin/chpasswd
  #     instead of "echo "root:$new_passwd" | /usr/sbin/chpasswd"
  #     Then by running drbl-client-root-passwd we can see which lib*.so* is missing.
  # //NOTE// /lib* includes /lib and /lib64
  PAM_need_files="/lib*/security/ /usr/lib*/libcrack*.so* /usr/lib*/cracklib_dict.* /lib*/libnss_files*.so* /lib/*/libnss_files*.so* /usr/lib/*/libnss_files*.so* /lib*/libnsl*.so* /lib/*/libnss_nis*.so* /usr/lib/*/libnss_nis*.so*  /usr/lib/pwdutils/*.so* /lib*/libcrypt*.so* /usr/lib*/libcrypto*.so* /lib/xcrypt/libxcrypt*.so* /lib/*/security/*pam*.so* /lib/security/*pam*.so* /lib/*/libnsl*.so*  /lib/*/tls/i686/sse2/cmov/libnsl*.so* /lib/*/tls/cmov/libnsl*.so* /usr/lib/*/tls/i686/sse2/cmov/libnsl*.so* /usr/lib/*/tls/cmov/libnsl*.so* /lib/tls/*/libnsl*.so* /lib/tls/sse2/cmov/libnsl*.so* /lib/tls/cmov/libnsl*.so* /lib/*/libdbus*.so* /lib/*/tls/libdbus*.so*  /usr/lib/*/i686/libnsl*.so* /usr/lib*/libdbus*.so* /usr/lib/cmov/libdbus*.so* /lib/*/libcap*.so* /lib/libcap*.so* /usr/lib/libcap*.so* /lib/libck-connector*.so* /lib/*/libck-connector*.so* /usr/lib/libck-connector*.so* /lib/*/librt*.so* /usr/lib/*/librt*.so* /lib/*/libcgmanager*.so* /lib/*/libnih*.so* /lib/*/*pam*.so* /lib/*/libpthread*.so*"
  chpasswd_lib_need="$(LC_ALL=C ldd /usr/sbin/chpasswd | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')"
  echo_lib_need="$(LC_ALL=C ldd /bin/echo | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')"
  export DESTDIR="$newroot"
  for imod in $chpasswd_lib_need $echo_lib_need; do
    # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
    [ "$imod" = "linux-vdso.so.1" ] && continue
    [ "$imod" = "linux-gate.so.1" ] && continue
    #cp --parents -d $imod $newroot
    copy_exec_drbl $imod "$(LC_ALL=C dirname $imod)"
  done
  # /bin/echo is necessary for chpasswd
  cp --parents -d /bin/echo $newroot
  cp --parents -d /usr/sbin/chpasswd $newroot
  # cp --parents /usr/bin/strace $newroot

  #cp --parents -r $PAM_need_files $newroot
  for ipam in $PAM_need_files; do
    [ -n "$(ls $ipam 2>/dev/null)" ] && cp --parents -r $ipam $newroot
  done
  # we need sh to run the script, borrow it from mkpxeinitrd-net's busybox
  cp /usr/lib/mkpxeinitrd-net/initrd-skel/bin/sh $newroot/bin
} # end of create_chpasswd_env

#
#create_passwd_env() {
#  local newroot="$1"
#  [ -z $newroot ] && exit 1
#  # /lib* includes /lib and /lib64
#  PAM_need_files="/lib*/security/ /usr/lib*/libcrack*.so* /usr/lib*/cracklib_dict.* /lib*/libnss_files*.so* /lib*/libnsl*.so* /usr/lib/pwdutils/*.so*"
#  passwd_lib_need=$(ldd /usr/bin/passwd | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
#  for imod in $passwd_lib_need; do
#    cp --parents $imod $newroot
#  done
#  cp --parents /usr/bin/passwd $newroot
#
#  # /bin/echo is necessary for passwd --stdin
#  cp --parents /bin/echo $newroot
#
#  cp --parents -r $PAM_need_files $newroot
#  # we need sh to run the script, borrow it from mkpxeinitrd-net's busybox
#  cp /usr/lib/mkpxeinitrd-net/initrd-skel/bin/sh $newroot/bin
#}

clean_passwd_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
#  passwd_lib_need=$(ldd /usr/bin/passwd | cut -d" " -f3)
#  [ -f "$newroot/usr/bin/passwd" ] && rm -f $newroot/usr/bin/passwd
#  [ -f "$newroot/bin/echo" ] && rm -f $newroot/bin/echo
#  for f2rm in $passwd_lib_need; do
#    [ -f $newroot/$f2rm ] && rm -f $newroot/$f2rm
#  done
#  for f2rm in $PAM_need_files; do
#    [ -f $newroot/$f2rm ] && rm -f $newroot/$f2rm
#  done
#  [ -f "$newroot/bin/sh" ] && rm -f $newroot/bin/sh
  for d2rm in bin lib usr; do
    if [ -d "$newroot/$d2rm" ]; then
      [ -n "$verbose" ] && echo "Cleaning the unnecessary directory $newroot/$d2rm ..."
      rm -rf $newroot/$d2rm
    fi
  done
} # end of clean_passwd_env
#
clean_chpasswd_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  for d2rm in bin lib usr; do
    if [ -d "$newroot/$d2rm" ]; then
      [ -n "$verbose" ] && echo "Cleaning the unnecessary directory $newroot/$d2rm ..."
      rm -rf $newroot/$d2rm
    fi
  done
} # end of clean_chpasswd_env

# check if the user input /dev/hda, /dev/hdb...
check_input_hd() {
    local target_hd="$1"
    case "$target_hd" in
	 [hsv]d[a-z])
	   continue
	   ;;
	 *)
	  echo "Unknown HD device! Program stop!"
          Usage
	  exit 1
    esac
}

## description:
##   convert devfs names into normal short ones, written by Tom Rini.
fixdevfs() {
    ## get partition number, if any
    local PARTNUM="${1##*[a-z]}"
    ## Find the bus type.
    local TYPE="$(v=${1#/dev/} ; echo ${v%/host*})"
    ## Find the host number.
    local HOST="$(v=${1#/dev/*/host} ; echo ${v%/bus*})"
    ## Find the bus number.
    local BUS="$(v=${1#/dev/*/bus} ; echo ${v%/tar*})"
    ## Find the target.
    local TARGET="$(v=${1#/dev/*/target} ; echo ${v%/lun*})"

    case "$TYPE" in
	ide)
	case "$HOST" in
	    0)
	    case "$TARGET" in
		0)
		local DEV=hda
		;;
		1)
		local DEV=hdb
		;;
	    esac
	    ;;
	    1)
	    case "$TARGET" in
		0)
	        local DEV=hdc
	        ;;
		1)
		local DEV=hdd
		;;
	    esac
	    ;;
	    2)
	    case "$TARGET" in
		0)
	        local DEV=hde
	        ;;
		1)
		local DEV=hdf
		;;
	    esac
	    ;;
	    3)
	    case "$TARGET" in
		0)
	        local DEV=hdg
	        ;;
		1)
		local DEV=hdh
		;;
	    esac
	    ;;
	    *)
		echo "${1#/dev/}"
		#echo "Unable to translate this device, try again without devfs."
		return 1
	esac
	local DEV="${DEV}${PARTNUM}"
	echo "$DEV"
	return 0
	;;
	scsi)
	local LUN="$(v=${1#/dev/*/lun} ; echo ${v%/*})"

	## In this case, we need to figure out what number our device is
	local DEVCOUNT=0

	## copy scsi file into a variable removing "Attached Devices"
	## which is the first line. this avoids a lot of
	## [incmopatible] crap later, and improves readability.

	## find number of lines once and recycle that number, to save
	## some time (linecount is a bit slow). subtract one line
	## to scrap Attached Devices:

	local SCSILINES="$(($(wc -l /proc/scsi/scsi | cut -d' ' -f1) - 1))"
	local PROCSCSI="$(cat /proc/scsi/scsi | tail -n $SCSILINES)"

	for i in $(seq $(($SCSILINES / 3))) ; do

	    ## put every scsi device into one single line
	    local DEVINFO="$(echo "$PROCSCSI" | head -n $(($i * 3)) | tail -n 3)"
	    [ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVINFO=$DEVINFO"

	    ## cut the type field, expect "Direct-Access" later.
	    local DEVTYPE="$(v=$(echo ${DEVINFO##*Type: }) ; echo ${v%% *})"
	    [ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVTYPE=$DEVTYPE"

	    if [ "$DEVTYPE" = "Direct-Access" ] ; then
		## Lets find out some more information
		## get the device id.
		local DEVID="$(v=$(echo ${DEVINFO##*Id: }) ; n=$(echo ${v%% *}) ; echo ${n#*0})"
		[ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVID=$DEVID"

		## get the device lun.
		local DEVLUN="$(v=$(echo ${DEVINFO##*Lun: }) ; n=$(echo ${v%% *}) ; echo ${n#*0})"
		[ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVLUN=$DEVLUN"

		## get the device channel.
		local DEVCHAN="$(v=$(echo ${DEVINFO##*Channel: }) ; n=$(echo ${v%% *}) ; echo ${n#*0})"
		[ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVCHAN=$DEVCHAN"

		## get the scsi host id.
		local DEVHOST="$(v=$(echo ${DEVINFO##*Host: scsi}) ; echo ${v%% *})"
		[ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVHOST=$DEVHOST"

		local DEVCOUNT="$(($DEVCOUNT + 1))"
		[ "$DEBUG" = 1 ] && echo 1>&2 "$PRG: DEBUG: fixdevfs: DEVCOUNT=$DEVCOUNT"
		if [ "$DEVHOST" = "$HOST" -a "$DEVCHAN" = "$BUS" -a \
		    "$DEVID" = "$TARGET" -a "$DEVLUN" = "$LUN" ] ; then
		    local DEV="sd$(smalltr $DEVCOUNT)${PARTNUM}"
		    echo "$DEV"
		    return 0
		fi
	    fi
	done
	echo "${1#/dev/}"
	#echo "Unable to translate this device, try again without devfs."
	return 1
	;;
	*)
	echo "${1#/dev/}"
	#echo "Unknown bus"
	return 1
	;;
    esac
    ## we should never get here
    return 1
}

# get dhcpd interface
get_dhcpd_interface() {
  local INTERFACES INTERFACESv4 INTERFACES_TMP
  if [ -e /etc/debian_version ]; then
    # Debian
    . $SYSCONF_PATH/$DHCP_SRV_NAME
  elif [ -e /etc/SuSE-release ]; then
    # SuSE
    . $SYSCONF_PATH/$DHCP_SRV_NAME
    INTERFACES="$DHCPD_INTERFACE"
  else
    # RH-like
    # The content of /etc/sysconfig/dhcpd file:
    # E.g. DHCPDARGS="-p 67 eth0 eth1";
    # //NOTE// Although /etc/sysconfig/dhcpd is not used anymore by CentOS/Fedora which uses systemd, we still can use it as the config file for dhcpd, because it's easier for us to parse compared with dhcpd.conf.
    # Det the setting of dhcp server
    . $SYSCONF_PATH/$DHCP_SRV_NAME
    # collect those interface, filter out other options, such as -p 60
    INTERFACES=""
    for ieth in $DHCPDARGS; do
       # For CentOS >= 7, NIC device name is changed as "Predictable Network Interface Names".
       # Ref: http://www.freedesktop.org/wiki/Software/systemd/PredictableNetworkInterfaceNames/
       # Names incorporating Firmware/BIOS provided index numbers for on-board devices (example: eno1)
       # Names incorporating Firmware/BIOS provided PCI Express hotplug slot index numbers (example: ens1)
       # Names incorporating physical/geographical location of the connector of the hardware (example: enp2s0)
       # Names incorporating the interfaces's MAC address (example: enx78e7d1ea46da)
       # Classic, unpredictable kernel-native ethX naming (example: eth0)
       INTERFACES_TMP="$(echo $ieth | grep -Eo '(eth[[:digit:]]+|en[[:print:]]+|p[[:digit:]]+p[[:digit:]]+)')"
       INTERFACES="$INTERFACES $INTERFACES_TMP"
    done
  fi
  # The variable might be INTERFACES or INTERFACESv4 (newer isc-dhcp-server)
  echo $INTERFACES $INTERFACESv4
} # end of get_dhcpd_interface

# HD dma status
check_hd_dma() {
   # input example: /dev/hda
   # return 0/1, 0: DMA off, 1: DMA on
   local hd_dev=$1
   DMA_status=$(hdparm -d $hd_dev 2>/dev/null | grep using_dma | awk  '{print $3}')
   echo "$DMA_status"
}

# turn on hd dma
turn_on_hd_dma() {
    local hd_dev="$1"
    if [ -z "$hd_dev" ]; then
      echo "To turn on HD dma, you have to specify the HD dev!"
      exit 1
    fi
    # Only IDE (/dev/hda) need to be turned on DMA.
    [ -z "$(echo $hd_dev | grep -F "/dev/hd")" ] && return 3
    #
    echo "*******************************************"
    echo "Try to turn on the harddisk \"$hd_dev\" DMA..."
    if [ "$(check_hd_dma $hd_dev)" = "0" ]; then
      # turn on DMA if it's off (0)
      hdparm -d1m1c1 $hd_dev
    fi
    # check the result
    DMA="$(check_hd_dma $hd_dev)"
    if [ -n "$DMA" ]; then
       # This is IDE device, we can get DMA status
       [ "$DMA" -eq 0 ] && echo "Warning!!! Failed to turn on harddisk \"$hd_dev\" DMA... The clone performance might be NOT good..." && sleep 5
    else
       # This is SCSI device, we can not get DMA status
       echo "No HD DMA information, maybe this not a IDE device!"
    fi
    echo "*******************************************"
} # end of turn_on_hd_dma

# do not let screen be blank
#
screen_not_blank() {
  if [ "$ocs_screen_blank" != "no" ]; then
    setterm --blank 0 --powersave off 2>/dev/null
  fi
}

# set passwd login for single user mode
set_clients_rc1_passwd() {
  local rc1_sulogin="~~:S:wait:/sbin/sulogin"
  IP_LIST=$*
  # make a flag "LIST_HOST"
  [ -n "$IP_LIST" ] && LIST_HOST="on"

  for ihost in $drblroot/*; do
     # skip those IP not listed in the $IP_LIST
     if [ "$LIST_HOST" = "on" ]; then
       [ -z "$(echo $IP_LIST | grep ${ihost##/*/})" ] && continue
     fi

    if ! grep -qE ^$rc1_sulogin $ihost/etc/inittab 2>/dev/null; then
      echo "Set the single user password for client ${ihost##/*/}, this will be safer..."
      cat <<-EOF >> $ihost/etc/inittab

# Single User Mode Password, added by DRBL
$rc1_sulogin
EOF
    fi
  done
}
#
get_lang_index() {
   local lang=$1
   local language
   case "$lang" in
      "2")
           language="zh_TW.UTF-8"
           ;;
       *)
           language="en_US.UTF-8"
           ;;
   esac
   echo $language
}

check_kernel_nfsd_tcp_config() {
  # note the kernel should be the one is using in the drbl server
  kernel_ver=$(uname -r)
  # check if /boot/config-$kernel_ver exists
  # kernel config is either in /boot/ 
  kernel_config="/boot/config-$kernel_ver"
  echo "Checking server kernel config \"$kernel_config...\""
  if [ ! -f $kernel_config ]; then 
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$kernel_config does NOT exist!"
    echo "I can not judge whether NFS over TCP is supported in the kernel you are using!!!"
    echo "We will assume that the NFS server use UDP protocol!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    protocol="udp"
  else
    # we assume the the priority is higher for EXT2, i.e. EXT2 option will overwrite the CRAMFS.
    if [ -n "$(grep "^CONFIG_NFSD_TCP=y" $kernel_config)" ]; then
      protocol="tcp"
    else
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "$kernel_config is found but NFS over TCP is not supported in the kernel you are using for the DRBL clients!!!"
      echo "We will use NFS over UDP !"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      protocol="udp"
    fi
  fi
  case "$protocol" in
    [tT][cC][pP])
       rc=0 
       ;;
    [uU][dD][pP])
       rc=1 
       ;;
  esac
  return $rc
}

switch_clients_init() {
   # input: client_init IP_LIST
   # if IP_LIST is none, this function will process all the clients.
   local CLIENT_INIT
   local IP_LIST
   CLIENT_INIT=$1
   shift
   IP_LIST=$*
   # make a flag "LIST_HOST"
   [ -n "$IP_LIST" ] && LIST_HOST="on"
   [ -z "$CLIENT_INIT" ] && echo "No specified mode for client inittab!!! Program stop!!!" && exit 1
   for host in $drblroot/*; do
     # skip those IP not listed in the $IP_LIST
     if [ "$LIST_HOST" = "on" ]; then
       [ -z "$(echo $IP_LIST | grep ${host##/*/})" ] && continue
     fi

     echo "Setting the graphic mode for node IP = $(basename $host)..."
     # set the init to 5, i.e. default is X
     /usr/bin/perl -p -i -e "s/^id:[1-5]:initdefault:/id:$CLIENT_INIT:initdefault:/g" $host/etc/inittab
   done
}

# This "GREP_NEWER" program is borrowed from http://staff.washington.edu/corey/new-patches.cgi
# The original author:
# Corey Satten, corey @ cac.washington.edu, 06/26/03, release 1.8
# For the latest version visit: http://staff.washington.edu/corey/tools.html
#
# Modified by Blake Huang and Steven Shiau to use in DRBL
GREP_NEWER='
    # Function newer:
    # Return 1 if second arg is "newer" than the first arg, else return 0.
    #
    # Because extra dotted fields before a hyphen are more significant
    # than those after a hyphen, first split on hyphens, then loop over
    # dotted fields passing the hard alphanumerics to function "compare"
    # for further splitting and comparing.
    #
    # eg.  older bind-utils-8.2.2_P5-9     and  older gzip-1.2.4-14
    #      newer bind-utils-8.2.2_P7-0.6.2 and  newer gzip-1.2.4a-2
    #
    #      older apmd-3.0beta9-3           and  older rmt-0.4b4-11 
    #      newer apmd-3.0final-2           and  newer rmt-0.4b19-5.6x

    function newer(a, b,    na1, nb1, na, nb, minn, i, j) {
	#printf("newer called with %s %s\n", a, b)
	if ('"${EFLAG-0}"') return a!=b
	if (O) {na=a; a=b; b=na}
	na1 = split(a, A1, /-/)
	nb1 = split(b, B1, /-/)
	if (na1 != nb1) {
	  #printf "unsure about %s and %s\n", a, b > "/dev/stderr"
	  return 1 }
	for (j=1; j<=na1; ++j) {
	  na = split(A1[j], A, /\./)
	  nb = split(B1[j], B, /\./)
	  minn = na < nb ? na : nb
	  for (i=1; i<=minn; ++i) {
	    if ('"${DEBUG-0}"') \
	      printf(" newer%d comparing %s %s\n", i, A[i], B[i])>"/dev/stderr"
	    if ((A[i] B[i]) ~ /^[0-9]+$/) {
	      if (A[i]+0 < B[i]+0) return 1
	      if (A[i]+0 > B[i]+0) return 0 }
	    else if (A[i] "" != B[i] "") return compare(A[i], B[i])
	    }
	  if (nb > na) return 1
	  if (nb < na) return 0
	  }
	return 0
	}

    # Function compare (called only by function newer):
    # Return 1 if second arg is "newer" than the first arg, else return 0.
    #
    # This is harder than it looks: consider "v9" vs "v10a", etc.
    # split out and compare alternating fields of numeric and non-numeric

    function compare (a, b,    xa, xb) {
	#printf(" compare called with %s %s\n", a, b)
	while (length(a) && length(b)) {
	  if (a ~ /^[0-9]/) {
	    match(a, /^[0-9]+/)
	    xa = substr(a, 1, RLENGTH); a = substr(a, RLENGTH+1) }
	  else {
	    match(a, /^[^0-9]+/)
	    xa = substr(a, 1, RLENGTH); a = substr(a, RLENGTH+1) }
	  if (b ~ /^[0-9]/) {
	    match(b, /^[0-9]+/)
	    xb = substr(b, 1, RLENGTH); b = substr(b, RLENGTH+1) }
	  else {
	    match(b, /^[^0-9]+/)
	    xb = substr(b, 1, RLENGTH); b = substr(b, RLENGTH+1) }
	    #printf("  compare2 %s %s <%s> <%s>\n", xa, xb, a, b)
	  if ( (xa xb) ~ /^[0-9]+$/) {
	    if (xa+0 < xb+0) return 1
	    if (xa+0 > xb+0) return 0 }
	  else {
	    if (xa "" < xb "") return 1
	    if (xa "" > xb "") return 0 }
	  }
	if (length(b)) return 1
	else return 0
	}
    '
#
set_specific_host_pxe_conf() {
  local HOSTS="$*"
  local pxecfg pxecfg_MAC pxecfg_MIP OCS_TMP IP
  # prepare the HOSTNAME-IP-MAC table
  OCS_TMP=`mktemp /tmp/ocs_clean_tmp.XXXXXX`
  trap "[ -f "$OCS_TMP" ] && rm -f $OCS_TMP" HUP INT QUIT TERM EXIT
  parse_dhcpd_conf $OCS_TMP

  for ih in $HOSTS; do
    case "$ih" in
      *.*.*.*)
        # list by IP
	# the pxecfg will like "C0A80001"
	pxecfg="$(drbl-gethostip $ih)"
        # These files look like: 01-MAC address (with ":" -> "-"),
	# We'd better to clean the 01-MAC file if it exists since maybe it's created by ocsmgrd when received the results from client in the previous save/restoration. Since 01-MAC has higher priority than "C0A80001" style file in pxelinux, this is a must if we can find it, we have to remove it.
	# TODO: What if no MAC address setting in dhcpd.conf ? Then $OCS_TMP will be empty, then... ?
        pxecfg_MAC="01-$(grep ${ih} $OCS_TMP | awk -F" " '{print $3}' | tr ":" "-")"
        [ -f "$PXELINUX_DIR/$pxecfg_MAC" ] && rm -f $PXELINUX_DIR/$pxecfg_MAC
        ;;
      *:*:*:*:*:*)
        # list by MAC
	# for an Ethernet (ARP type 1) with address 88:99:AA:BB:CC:DD it would search for the filename 01-88-99-aa-bb-cc-dd (lowercase)
	pxecfg="$(echo $ih | tr "[A-Z]" "[a-z]" | tr ":" "-")"
	# append "01-" in the beginning
	pxecfg="01-$pxecfg"
	# We'd better to clean the IP-based setting file if it exists since maybe it's created by ocsmgrd when received the results from client in the previous save/restoration. Although 01-MAC has higher priority than "C0A80001" style file in pxelinux, this NOT a must if we can find it, but we remove it to avoid confusion.
        IP="$(grep -E ${ih} $OCS_TMP | awk -F" " '{print $2}')"
	pxecfg_MIP="$(drbl-gethostip $IP)"
        [ -f "$PXELINUX_DIR/$pxecfg_MIP" ] && rm -f $PXELINUX_DIR/$pxecfg_MIP
        ;;
    esac
    echo -n "Generate the PXE config file for host $ih ... "
    cp -f $PXELINUX_DIR/default_skeleton $PXELINUX_DIR/$pxecfg
    echo "done!"
  done
  [ -f "$OCS_TMP" ] && rm -f $OCS_TMP
} # end of set_specific_host_pxe_conf

# function to get the pxecfg image block line number
get_pxecfg_image_block() {
     local IMG_NAME="$1"
     local PXE_CONF_TMP="$2"
     [ -z "$IMG_NAME" ] && exit 1
     # By using
     # grep -Ei -n '^[[:space:]]*label[[:space:]]+.*([[:space:]]|$)+' /tftpboot/nbi_img/pxelinux.cfg/default | grep -A1 -E "label[[:space:]]+drbl([[:space:]]|$)+"
     # 10:label drbl
     # 17:label local
     # so we know we can replace the one between line no. 10 and 17
     between_lines="$(LC_ALL=C grep -Ei -n "^[[:space:]]*label[[:space:]]+.*([[:space:]]|$)+" $PXE_CONF_TMP | grep -Ei -A1 "label[[:space:]]+$IMG_NAME([[:space:]]|$)+" | cut -d":" -f1)"
     begin_line="$(LC_ALL=C echo $between_lines | awk -F" " '{print $1}')"
     end_line="$(LC_ALL=C echo $between_lines | awk -F" " '{print $2}')"
     # if end_line is nothing, it must be the last block, i.e. we can not find the next [.*]
     if [ -z "$end_line" ]; then
       end_line="$(LC_ALL=C wc -l $PXE_CONF_TMP | awk -F" " '{print $1}')"
     else
       # if not nothing, backword one line
       end_line="$(($end_line - 1))"
     fi
     echo "$begin_line $end_line"
} # end of get_pxecfg_image_block
check_img_in_pxe_cfg() {
     local IMG="$1"
     local PXE_CONF_TMP="$2"
     if [ -z "$IMG" ]; then
        [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
        echo "You must specify the image name! Program terminated!!!"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        exit 1
     fi
     if ! grep -Eiq "^[[:space:]]*label[[:space:]]+$IMG" $PXE_CONF_TMP; then
        [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
        echo "Unable to find the image ($IMG) label! Make sure the $IMG is labeled in $PXE_CONF_TMP! Program terminated!!!"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        exit 1
     fi
} # end of check_img_in_pxe_cfg
sub_default_pxe_img() {
     local IMG="$1"
     local PXE_CONF_TMP="$2"
     local MENU_LABEL="$3"
     check_img_in_pxe_cfg $IMG $PXE_CONF_TMP
     # turn off all MENU DEFAULT
     echo "Turn off all MENU DEFAULT in $PXE_CONF_TMP... "
     perl -pi -e "s/^(#|[[:space:]])*MENU DEFAULT.*/  # MENU DEFAULT/i" $PXE_CONF_TMP
     all_label="$(awk '/^[[:space:]]*label[[:space:]]+.*([[:space:]]|$)+/ {print $2}' $PXE_CONF_TMP)"
     # 2006/09/10 Steven commented this, we'd better keep the way pxelinux config is.
     #for i in $all_label; do
     #  if [ -z "$(echo $IMG_SHOW_IN_MENU | grep -i $i)" ]; then
     #    [ -n "$VERBOSE" ] && echo "Hide image $i"
     #    hide_reveal_pxe_img $i hide $PXE_CONF_TMP
     #  fi
     #done

     # turn on MENU DEFAULT & turn off MENU HIDE for the specified image
     lines="$(get_pxecfg_image_block $IMG $PXE_CONF_TMP)"
     begin_line="$(echo $lines | awk -F" " '{print $1}')"
     end_line="$(echo $lines | awk -F" " '{print $2}')"
     echo "Make \"$IMG\" as default label in $PXE_CONF_TMP."
     sub_def_cmd="if ($begin_line..$end_line) {s/^(#|[[:space:]])*MENU DEFAULT.*/  MENU DEFAULT/i}"
     sub_hide_cmd="if ($begin_line..$end_line) {s/^(#|[[:space:]])*MENU HIDE.*/  # MENU HIDE/i}"
     perl -pi -e "$sub_def_cmd" $PXE_CONF_TMP
     perl -pi -e "$sub_hide_cmd" $PXE_CONF_TMP

     if [ -n "$MENU_LABEL" ]; then
       echo The MENU LABEL is \"$MENU_LABEL\"
       sub_menu_label_cmd="if ($begin_line..$end_line) {s|^[[:space:]]*MENU LABEL.*|  MENU LABEL $MENU_LABEL|i}"
       perl -pi -e "$sub_menu_label_cmd" $PXE_CONF_TMP
     fi
} # end of sub_default_pxe_img
# use script hide_reveal_pxe_img instead of fnction.
#hide_reveal_pxe_img() {
#     local IMG="$1"
#     local ACT="$2"
#     local PXE_CONF_TMP="$3"
#     check_img_in_pxe_cfg $IMG $PXE_CONF_TMP
#     # turn off MENU DEFAULT & turn on MENU HIDE for the specified image
#     lines=$(get_pxecfg_image_block $IMG $PXE_CONF_TMP)
#     begin_line=$(echo $lines | awk -F" " '{print $1}')
#     end_line=$(echo $lines | awk -F" " '{print $2}')
#     case "$ACT" in
#       "hide")
#         [ -n "$VERBOSE" ] && echo "Hide $IMG in $PXE_CONF_TMP... "
#         sub_act_cmd="if ($begin_line..$end_line) {s/^(#|[[:space:]])*MENU HIDE.*/  MENU HIDE/i}"
#         ;;
#       "reveal")
#         [ -n "$VERBOSE" ] && echo "Reveal $IMG in $PXE_CONF_TMP... "
#         sub_act_cmd="if ($begin_line..$end_line) {s/^(#|[[:space:]])*MENU HIDE.*/  # MENU HIDE/i}"
#         ;;
#     esac
#     perl -pi -e "$sub_act_cmd" $PXE_CONF_TMP
#}
#
delete_label_block_pxe_img() {
  local LABEL="$1"
  local PXE_CONF_TMP="$2"
  local lines begin_line end_line rc
  [ -z "$LABEL" -o -z "$PXE_CONF_TMP" ] && return 1
  lines=$(get_pxecfg_image_block $LABEL $PXE_CONF_TMP)
  begin_line=$(echo $lines | awk -F" " '{print $1}')
  end_line=$(echo $lines | awk -F" " '{print $2}')
  # delete lines between $begin_line and $end_line
  perl -i -ne "print unless $begin_line..$end_line" $PXE_CONF_TMP
  rc=$?
  return $rc
} # end of delete_label_block_pxe_img
#
delete_menuentry_block_grub_img() {
  local ENTRY_ID="$1"
  local GRUB_CONF_TMP="$2"
  local lines begin_line end_line rc
  [ -z "$ENTRY_ID" -o -z "$GRUB_CONF_TMP" ] && return 1
  if [ -n "$GRUB_CONF_TMP" -a ! -e "$GRUB_CONF_TMP" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF_TMP not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  lines="$(get_grub_efi_image_block "--id $ENTRY_ID" $GRUB_CONF_TMP)"
  begin_line=$(echo $lines | awk -F" " '{print $1}')
  end_line=$(echo $lines | awk -F" " '{print $2}')
  # delete lines between $begin_line and $end_line
  perl -i -ne "print unless $begin_line..$end_line" $GRUB_CONF_TMP
  rc=$?
  return $rc
} # end of delete_label_block_pxe_img
#
ask_lang_set() {
  local language_opt="$1"
  local chosen_lang_var
  # lang will be the global variable
  # get the language
  if [ -z "$language_opt" ]; then
    # Try the Environment variable "LC_ALL", then "LANG"
    if [ -n "$LC_ALL" ]; then
      chosen_lang_var="$LC_ALL"
    elif [ -n "$LANG" ]; then
      chosen_lang_var="$LANG"
    fi
    # Normally we use the locale format like: en_US.UTF-8, however, it's possible it is en_US.utf8. Therefore here we format it to be *.UTF-8.
    chosen_lang_var="$(LC_ALL=C echo $chosen_lang_var | sed -e "s/\.utf8/.UTF-8/g")"
    if [ -n "$chosen_lang_var" -a -e "$DRBL_SCRIPT_PATH/lang/bash/$chosen_lang_var" ] ; then
      lang_answer="$chosen_lang_var"
    else
      lang_answer="en_US.UTF-8"
    fi
  elif [ "$language_opt" = "ask" -o "$language_opt" = "a" ]; then
    # Language
    echo "Language?".
    echo "[0]: English"
    echo "[2]: Traditional Chinese (UTF-8, Unicode) - Taiwan"
    echo -n "[0] "
    read lang_answer
    [ -z "$lang_answer" ] && lang_answer="en_US.UTF-8"
  else
    lang_answer="$language_opt"
  fi
} # end of ask_lang_set

load_lang_set() {
  lang_answer=$1
  # The language files are en, tw.UTF-8, we have to format the input parameter.
  case "$lang_answer" in
     2|zh_TW.UTF-8|zh_TW.utf8|tw.UTF-8|tw.utf8)
        lang="zh_TW.UTF-8"
        ;;
     C)
        lang="en_US.UTF-8"
        ;;
     *)
        if [ -n "$lang_answer" -a -e "$DRBL_SCRIPT_PATH/lang/bash/$lang_answer" ] ; then
          lang="$lang_answer"
        else
          lang="en_US.UTF-8"
        fi
  esac
  
  # get the l10n message
  if [ -n "$lang" -a -e "$DRBL_SCRIPT_PATH/lang/bash/$lang" ] ; then
    . $DRBL_SCRIPT_PATH/lang/bash/$lang
  elif [ -n "$lang" -a -e "$DRBL_SCRIPT_PATH/lang/bash/${lang%.UTF-8}" ] ; then
    . $DRBL_SCRIPT_PATH/lang/bash/${lang%.UTF-8}
  else
    echo "No such language option '$lang'!!!"
    exit 1
  fi
} # end of load_lang_set
#
ask_and_load_lang_set() {
  local language_opt="$1"
  ask_lang_set $language_opt
  load_lang_set $lang_answer
} # end of ask_and_load_lang_set

#
language_help_prompt_by_idx_no() {
  echo " -l, --language INDEX Set the language to be shown by index number:"
  echo "       [0|en_US.UTF-8]: English,"
  echo "       [2|zh_TW.UTF-8]: Traditional Chinese (UTF-8, Unicode) - Taiwan"
  echo "       [a|ask]: Prompt to ask the language index"
  echo " This option is for backward compatibility. It's recommended to use locales to assign that."
}
#
language_help_prompt_by_idx_name() {
  echo "-ln  NAME    Set the language to be shown by index name, not number, such as en_US.UTF-8, zh_TW.UTF-8"
}

# For update-rc.d in Debian
prepare_update_rc_d_env() {
  local newroot="$1"
  local perl_lib_need insserv_lib_need
  [ -z "$newroot" ] && exit 1
  # for update-rc.d
  cp -f --parents /usr/sbin/update-rc.d $newroot
  cp -f --parents /usr/bin/perl $newroot
  perl_lib_need="$(LC_ALL=C ldd /usr/bin/perl | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')"
  export DESTDIR="$newroot"
  for imod in $perl_lib_need; do
    # Skip linux-vdso.so.1 and linux-gate.so.1, the virtual DSO, a shared object exposed by the kernel. They do not exist on the file system. Ref: http://ilivetoseek.wordpress.com/2011/10/24/linux-gate-so-1-or-linux-vdso-so-1/ 
    [ "$imod" = "linux-vdso.so.1" ] && continue
    [ "$imod" = "linux-gate.so.1" ] && continue
    #cp --parents -d $imod $newroot
    copy_exec_drbl $imod "$(LC_ALL=C dirname $imod)"
  done
  # Ugly! we need some perl pm...
  mkdir -p $newroot/usr/{share,lib}
  # For perl >=5.20 in Debian, multi-arch is enabled
  # e.g. /usr/lib/i386-linux-gnu/perl, /usr/lib/x86_64-linux-gnu/perl/
  rsync -a /usr/share/perl $newroot/usr/share/
  if [ -n "$(ls /usr/lib/*perl* 2>/dev/null)" ]; then
    rsync -a /usr/lib/*perl* $newroot/usr/lib/
  fi
  if [ -d "/usr/lib/i386-linux-gnu/perl" ]; then
    mkdir -p $newroot/usr/lib/i386-linux-gnu/
    rsync -a /usr/lib/i386-linux-gnu/perl $newroot/usr/lib/i386-linux-gnu/
  fi
  if [ -d "/usr/lib/x86_64-linux-gnu/perl" ]; then
    mkdir -p $newroot/usr/lib/x86_64-linux-gnu/
    rsync -a /usr/lib/x86_64-linux-gnu/perl $newroot/usr/lib/x86_64-linux-gnu/
  fi

  # for insserv
  if type insserv &>/dev/null; then
    cp -f --parents /sbin/insserv $newroot
    insserv_lib_need="$(LC_ALL=C ldd /sbin/insserv | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')"
    for imod in $insserv_lib_need; do
      [ "$imod" = "linux-vdso.so.1" ] && continue
      [ "$imod" = "linux-gate.so.1" ] && continue
      cp --parents -d $imod $newroot
    done
  fi
} # end of prepare_update_rc_d_env

#
clean_update_rc_d_env() {
  local newroot="$1"
  [ -z "$newroot" ] && exit 1
  # we can clean files in /usr/bin and /usr/sbin in common_root because they are mount ponts.
  [ -f $newroot/usr/bin/perl ] && rm -f $newroot/usr/bin/perl 
  [ -f $newroot/usr/sbin/update-rc.d ] && rm -f $newroot/usr/sbin/update-rc.d
  perl_lib_need=$(LC_ALL=C ldd /usr/bin/perl | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
  for f2rm in $perl_lib_need; do
    [ -f $newroot/$f2rm ] && rm -f $newroot/$f2rm
  done
}

#
chk_deb_installed () {
  local pkg_name=$1
  local RC
  [ -z "$pkg_name" ] && exit 1
  # dpkg version 1.17.13 has a bug which fails to update /var/lib/dpkg/available in bootstrap environment.
  # Therefore the option --print-avail fails. We switched to use "dpkg -L".
  #dpkg-query --print-avail $pkg_name &>/dev/null
  dpkg -L $pkg_name &>/dev/null
  RC=$?
  return $RC
}
#
copy_rc1d_for_drbl_ssi() {
  # Note! use absolute path for template_cli 
  local template_cli="$1"
  echo -n "Copying files to $drbl_common_root/drbl_ssi for DRBL SSI... "
  mkdir -p "$drbl_common_root/drbl_ssi/rc1.d"
  if [ -z "$template_cli" ]; then
    for ih in $drblroot/*; do
      # use the 1st one drbl client we found as template
      if [ -d "$ih" ]; then
        template_cli="$ih"
        break
      fi
    done
  fi
  cp -af $template_cli/$RCX_ROOTDIR/rc1.d/* $drbl_common_root/drbl_ssi/rc1.d/
  echo "done!"
} # end of copy_rc1d_for_drbl_ssi
#
remove_rc1d_for_drbl_ssi() {
  # Note! use absolute path for template_cli 
  local template_cli="$1"
  echo -n "Resetting files of $drbl_common_root/drbl_ssi for DRBL SSI... "
  # we just clean the unnecessary files, keep the directory
  if [ -d "$drbl_common_root/drbl_ssi/rc1.d" ]; then
    rm -rf $drbl_common_root/drbl_ssi/rc1.d
  fi
  echo "done!"
} # end of remove_rc1d_for_drbl_ssi
#
prepare_gdm_custom_conf(){
  # For ubuntu 9.10, the gdm 2.28.1-0ubuntu does not put /etc/gdm/custom.conf in the deb. It will be added when user creates it.
  if [ -n "$($query_pkglist_cmd gdm 2>/dev/null | grep -F "/usr/share/doc/gdm/examples/custom.conf")" ]; then
   # It must be /etc/gdm/custom.conf. We prepare one if not exits.
   # (1) For server, since drbl-powerful-thin-client might need that:
   if [ ! -e "/etc/gdm/custom.conf" ]; then
     cp -a /usr/share/doc/gdm/examples/custom.conf /etc/gdm/custom.conf
   fi
   # (2) For client. We always use the one from /usr/share/doc/gdm/examples/custom.conf in case /etc/gdm/custom.conf is modified.
   cp -af /usr/share/doc/gdm/examples/custom.conf $drbl_common_root/etc/gdm/custom.conf
   if [ -z "$(grep -E "^\[daemon\]" $drbl_common_root/etc/gdm/custom.conf 2>/dev/null)" ]; then
     echo "" >> $drbl_common_root/etc/gdm/custom.conf
     echo "[daemon]" >> $drbl_common_root/etc/gdm/custom.conf
   fi
   GDM_CFG="/etc/gdm/custom.conf"
  fi
} # end of prepare_gdm_custom_conf
#
get_gdm_kdm_conf_filename() {
  # Get the gdm, kdm, mdm config:
  # Ex: this is the setting for gdm 2.13 before and kdm 2.x/3.x
  # GDM_CFG="/etc/X11/gdm/gdm.conf"
  # FAC_GDM_CFG="/etc/X11/gdm/factory-gdm.conf"
  # KDM_CFG="/etc/kde3/kdm/kdmrc"
  # MDM_CFG="/etc/mdm/mdm.conf"
  # For gdm 2.13 or later, different filenames, such as custom.conf, gdm.conf-custom and kdmrc, no more factory-gdm.conf
  # For Ubuntu 9.10, since upstart use /etc/init/gdm.conf, we have to exclude that.
  GDM_CFG=""
  # The order "gdm.conf-custom custom.conf gdm.conf" is important, we put gdm.conf as the last one, since we wan to get only one $GDM_CFG, gdm.conf is always the last one to choose, if we can get gdm.conf-custom or custom.conf, we use that first
  # Note: Even in SuSE, gdm.conf/custom.conf is in /etc/opt/gnome/gdm/gdm.conf, we can get it by rpm -ql gdm, unlike kdm. It's not necessary to put /etc/ in the beginning.
  # For OpenSuSE 11.1, /etc/gdm/custom.conf is from package gdm-branding-openSUSE, and there is another same file name /etc/dbus-1/system.d/gdm.conf from package gdm, and /etc/dbus-1/system.d/gdm.conf is NOT what we want.
  for ipkg in gdm3 gdm gdm-branding-openSUSE; do
    for ig in daemon.conf gdm.conf-custom custom.conf gdm.conf; do
      GDM_CFG="$($query_pkglist_cmd $ipkg 2>/dev/null | grep -E "\/$ig$" | grep -Ev "dbus" | grep -Evi "examples" | grep -Evi "\/etc\/init\/")"
      [ -n "$GDM_CFG" ] && break
    done
    [ -n "$GDM_CFG" ] && break
  done
  FAC_GDM_CFG="$($query_pkglist_cmd gdm 2>/dev/null | grep -E "\/factory-gdm.conf$")"
  if [ -z "$GDM_CFG" ]; then
    prepare_gdm_custom_conf
  fi

  # kdmrc maybe in package kdm (Debian-based), kdebase (FC), kdebase-kdm-config-file (Mandrake) or kdebase3-kdm (OpenSuSE)
  # In FC, there are 2 kdmrc:
  # /etc/X11/xdm/kdmrc
  # /etc/kde/kdm/kdmrc
  # But /etc/X11/xdm/kdmrc is actually linked to /etc/kde/kdm/kdmrc, so use either one will be ok.
  for ipkg in kde4-kdm kdm kdebase kdebase-kdm-config-file kdebase3-kdm; do
    KDM_CFG="$($query_pkglist_cmd $ipkg 2>/dev/null | grep -E "(\/kdmrc$)" | head -n 1)"
    if [ -n "$(echo $KDM_CFG | grep -E "^\/opt\/kde")" ]; then
      # For SuSE 10.1 or earlier, actually the config file is in /etc/opt/kde3/share/config/kdm/kdmrc, therefore put /etc/ in the beginning.
      # For SuSE 10.2, no more /etc/opt/kde3/share/config/kdm/kdmrc, only /opt/kde3/share/config/kdm/kdmrc
      # Ref: http://lists.opensuse.org/opensuse-factory/2006-09/msg00021.html
      [ -e "/etc/$KDM_CFG" ] && KDM_CFG=/etc/$KDM_CFG
    fi
    [ -n "$KDM_CFG" ] && break
  done
  # For lightdm
  if [ -e "/etc/lightdm/lightdm.conf" ]; then
    LIGHTDM_CFG=/etc/lightdm/lightdm.conf
  elif [ -d "/etc/lightdm/lightdm.conf.d" ]; then
    # For Ubuntu 13.10, lightdm 1.8.4 has different initial configration file. 
    # "/etc/lightdm/lightdm.conf" does not exist in the initial installation. 
    # While it will exist when a user configures that in the GUI.
    LIGHTDM_CFG=/etc/lightdm/lightdm.conf
  elif [ -d "/usr/share/lightdm/lightdm.conf.d" -a \
	 -e "/usr/share/doc/lightdm/lightdm.conf.gz" ]; then
    # For Ubuntu 14.04, lightdm 1.10 has different way. The /etc/lightdm/lightdm.conf.d has been moved to /usr/share/lightdm/lightdm.conf.d, and /etc/lightdm/lightdm.conf does not exist in the beginning. Only a sample file exists in "/usr/share/doc/lightdm/lightdm.conf.gz".
    if [ ! -f "$drbl_common_root/etc/lightdm/lightdm.conf" ]; then
      zcat "/usr/share/doc/lightdm/lightdm.conf.gz" > "$drbl_common_root/etc/lightdm/lightdm.conf"
    fi
    LIGHTDM_CFG=/etc/lightdm/lightdm.conf
  fi

  # For mdm : by Ceasar for Linuxmint
  if [ -e "/etc/mdm/mdm.conf" ]; then
    # for mdm v2.0
    MDM_CFG=/etc/mdm/mdm.conf
  fi

} # end of get_gdm_kdm_conf_filename
#
get_block_line_in_gdm_kdm() {
  local session="$1"
  local CFG_FILE="$2"
  [ -e "$CFG_FILE" ] || exit 1
  # Take xdmcp as an example:
  # Turn on the Enable=true in [xdmcp]
  # Enable=true
  # By using
  # grep -n "^\[.*\]" gdm.conf |grep -A1 "\[xdmcp\]"                 
  # We can get the results like:
  # 175:[xdmcp]
  # 210:[gui]
  # so we know we can replace the one between line no. 175 and 210
  between_lines="$(LC_ALL=C grep -n "^\[.*\]" $CFG_FILE |grep -i -A1 "\[$session\]" | cut -d":" -f1)"
  begin_line="$(echo $between_lines | awk -F" " '{print $1}')"
  end_line="$(echo $between_lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -a -z "$end_line"  ]; then
    # no this session in file. Use the last line to append.
    begin_line="$(LC_ALL=C wc -l $CFG_FILE | awk -F" " '{print $1}')"
    end_line="$(LC_ALL=C wc -l $CFG_FILE | awk -F" " '{print $1}')"
  elif [ -z "$end_line"  ]; then
    # if end_line is nothing, it must be the last block, i.e. we can not find the next [.*]
    end_line="$(LC_ALL=C wc -l $CFG_FILE | awk -F" " '{print $1}')"
  else
    # if not nothing, backword one line
    end_line="$(($end_line - 1))"
  fi
  echo "$begin_line $end_line"
} # end of get_block_line_in_gdm_kdm

#
get_dhcpdlease_dir() {
  if [ -e /etc/debian_version ]; then
    # Debian
    if [ -d "/var/lib/dhcp" ]; then
      DHCPDLEASE_DIR="/var/lib/dhcp"
    elif [ -d "/var/lib/dhcp3" ]; then
      DHCPDLEASE_DIR="/var/lib/dhcp3"
    fi
  elif [ -e /etc/SuSE-release ]; then
    # SuSE
    DHCPDLEASE_DIR="/var/lib/dhcp/db"
  else
    # RH-like
    # FC5: /var/lib/dhcpd/dhcpd.leases
    # RH 8.0/9, FC1-4: /var/lib/dhcp/dhcpd.leases
    # So this method is better:
    DHCPDLEASE_DIR="$(dirname `rpm -ql dhcp | grep -E "dhcpd.leases$"`)"
  fi
}
#
countdown () {
 local time_limit="$1"
 local i
       ( i="$time_limit"
         while [ "$i" -ne 0  ]; do
           echo -n "$i "
           sleep 1
           i=$((i-1))
         done
       )
}
#
is_drbl_client() {
  root_src="$(LC_ALL=C mount | grep -Ew "on /" | awk -F" " '{print $1}')"
  # Example for $root_src: 192.168.50.254:/tftpboot/node_root
  if [ -n "$(echo $root_src | grep -E "^[[:space:]]*([[:digit:]]+\.){3}[[:digit:]]+:/.*")" ] ; then
   rc=0
  else
   rc=1
  fi
  return $rc
}
#
add_param_in_pxelinux_cfg_drbl_related_block() {
  local PXE_CONF="$1"
  local param_tmp="$2"
  [ -z "$param_tmp" ] && echo "You have to assign param_tmp in function add_param_in_pxelinux_cfg_drbl_related_block!" && return 1
  for iblock in drbl drbl-terminal; do
    lines="$(get_pxecfg_image_block $iblock $PXE_CONF)"
    begin_line="$(LC_ALL=C echo $lines | awk -F" " '{print $1}')"
    end_line="$(LC_ALL=C echo $lines | awk -F" " '{print $2}')"
    tag_found="$(LC_ALL=C head -n $end_line $PXE_CONF | tail -n $(($end_line-$begin_line)) | grep -Ei "^[[:space:]]*append[[:space:]]*.*[[:space:]]+$param_tmp([[:space:]]+|$)")"
    if [ -z "$tag_found" ]; then
      sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)|\$1 $param_tmp|i}"
      perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
    fi
  done
} # end of add_param_in_pxelinux_cfg_drbl_related_block
#
del_param_in_pxelinux_cfg_drbl_related_block() {
  local PXE_CONF="$1"
  local param_tmp="$2"
  [ -z "$param_tmp" ] && echo "You have to assign param_tmp in function del_param_in_pxelinux_cfg_drbl_related_block!" && return 1
  for iblock in drbl drbl-terminal; do
    lines="$(get_pxecfg_image_block $iblock $PXE_CONF)"
    begin_line="$(LC_ALL=C echo $lines | awk -F" " '{print $1}')"
    end_line="$(LC_ALL=C echo $lines | awk -F" " '{print $2}')"
    tag_found="$(LC_ALL=C head -n $end_line $PXE_CONF | tail -n $(($end_line-$begin_line)) | grep -Ei "^[[:space:]]*append[[:space:]]*.*[[:space:]]+$param_tmp([[:space:]]+|$)")"
    if [ -n "$tag_found" ]; then
      sub_menu_label_cmd="if ($begin_line..$end_line) {s|$param_tmp||i}"
      perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
    fi
  done
} # end of del_param_in_pxelinux_cfg_drbl_related_block
#
ocs_advanced_param_post_mode_after_clone() {
  local ocs_parm # The file to output the result //NOTE// This is to be append, not overwritten.
  local default_postaction="reboot " # //NOTE// Extra space is required
  # For Clonezilla SE mode, we always ask this (reboot, poweroff...) no matter it's advanced or beginner mode.
  while [ $# -gt 0 ]; do
    case "$1" in
      -d|--default-menu) 
           shift; 
           if [ -z "$(echo $1 |grep ^-.)" ]; then
             # skip the -xx option, in case 
             default_postaction="$1"
             shift;
           fi
           [ -z "$default_postaction" ] && USAGE && exit 1
           ;;
       *)   break ;;
    esac
  done
  ocs_parm="$1"
  if [ -z "$ocs_postmode" ]; then
    # //NOTE// Extra space is required in the --default-item.
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" \
    --default-item "-p $default_postaction " \
    --menu "$msg_choose_post_mode_after_clone:" \
    0 0 0 $DIA_ESC \
    "-p reboot "    "$msg_ocs_param_p_reboot" \
    "-p poweroff "  "$msg_ocs_param_p_poweroff" \
    "-p choose "    "$msg_ocs_param_p_choose" \
    "-p true "      "$msg_ocs_param_p_true" \
    2>> $ocs_parm
  else
    echo "-p $ocs_postmode " >> $ocs_parm
  fi
} # end of ocs_advanced_param_post_mode_after_clone
#
ocs_sr_param_postaction_after_clone() {
  local ocs_parm="$1" # The file to output the result //NOTE// This is to be append, not overwritten.
  $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
  "$msg_mode: $ocs_mode_prompt" --menu "$msg_choose_post_mode_after_clone_1:" \
  0 0 0 $DIA_ESC \
  "-p choose "    "$msg_ocs_param_p_choose_1" \
  "-p true"       "$msg_enter_cml" \
  "-p reboot "    "$msg_ocs_param_p_reboot_1" \
  "-p poweroff "  "$msg_ocs_param_p_poweroff_1" \
  2>> $ocs_parm
} # end of ocs_sr_param_postaction_after_clone
#
ocs_onthefly_param_postaction_after_clone() {
  local ocs_parm="$1" # The file to output the result //NOTE// This is to be append, not overwritten.
  $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
  "$msg_mode: $ocs_mode_prompt" --menu "$msg_choose_post_mode_after_clone_1:" \
  0 0 0 $DIA_ESC \
  "-p choose "    "$msg_ocs_param_p_choose_1" \
  "-p true"       "$msg_enter_cml" \
  "-p reboot "    "$msg_ocs_param_p_reboot_1" \
  "-p poweroff "  "$msg_ocs_param_p_poweroff_1" \
  2>> $ocs_parm
} # end of ocs_onthefly_param_postaction_after_clone
#
show_z4_or_above_menu_or_not() {
  # function to show -z4, -z5/z5p, -z6/z6p options
  if type lzma &>/dev/null; then
    # "-z4"      "$msg_ocs_param_z4" \
    ocs_z4_option_1="-z4"
    ocs_z4_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z4")"
  fi
  if type xz &>/dev/null; then
    # "-z5"      "$msg_ocs_param_z5" \
    ocs_z5_option_1="-z5"
    ocs_z5_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z5")"

    # "-z5p"      "$msg_ocs_param_z5p" \
    ocs_z5p_option_1="-z5p"
    ocs_z5p_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z5p")"
  fi
  if type lzip &>/dev/null; then
    # "-z6"      "$msg_ocs_param_z6" \
    ocs_z6_option_1="-z6"
    ocs_z6_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z6")"
  fi
  if type plzip &>/dev/null; then
    # "-z6p"      "$msg_ocs_param_z6p" \
    ocs_z6p_option_1="-z6p"
    ocs_z6p_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z6p")"
  fi
  if type lrzip &>/dev/null; then
    # "-z7"      "$msg_ocs_param_z7" \
    ocs_z7_option_1="-z7"
    ocs_z7_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z7")"
  fi
  if type lz4 &>/dev/null; then
    # "-z8"      "$msg_ocs_param_z8" \
    ocs_z8_option_1="-z8"
    ocs_z8_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z8")"
    # "-z8p"      "$msg_ocs_param_z8p" \
    ocs_z8p_option_1="-z8p"
    ocs_z8p_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z8p")"
  fi
  if type zstd &>/dev/null; then
    # "-z9"      "$msg_ocs_param_z9" \
    ocs_z9_option_1="-z9"
    ocs_z9_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z9")"
  fi
  if type zstdmt &>/dev/null; then
    # "-z9p"      "$msg_ocs_param_z9p" \
    ocs_z9p_option_1="-z9p"
    ocs_z9p_option_2="$(rep_whspc_w_udrsc "$msg_ocs_param_z9p")"
  fi
} # end show_z4_or_above_menu_or_not
#
set_drbl_ocs_extra_param() {
  local mode
  # OCS_PARAM_TMP is a global variable
  local dev_
  local vol_size_tmp
  local ASK_VOL_SIZE=1
  local inst_grub_opt
  local set_y_opt="yes"  # Option to set option y* (y0/y1/y2)
  local default_postaction postaction_opt j2_switch_msg_1 j2_switch_msg_2 j2_switch_msg_3
  
  while [ $# -gt 0 ]; do
    case "$1" in
      -s|--skip-y) set_y_opt="no"; shift;;
      -p|--default-postaction) 
           shift; 
           if [ -z "$(echo $1 |grep ^-.)" ]; then
             # skip the -xx option, in case 
             default_postaction="$1"
             shift;
           fi
           [ -z "$default_postaction" ] && USAGE && exit 1
	   ;;
       *)  break ;;
    esac
  done
  
  mode="$1"
  dev_="$2"
  vol_size_tmp="$(mktemp /tmp/vol_size_tmp.XXXXXX)"

  if [ -z "$OCS_PARAM_TMP" ]; then
    echo "\"$OCS_PARAM_TMP\" was not assigned in function set_drbl_ocs_extra_param."
    echo "$msg_program_stop!"
    exit 1
  fi
  
  # If the mode is only for parts, we won't turn on "-g auto" option by default
  case "$dev_" in
    parts) inst_grub_opt="off"
  	 # For restoreparts, forget about clean mbr
  	 skip_clean_mbr_opt="on"
  	 ;;
        *) inst_grub_opt="on"
  	 # For restoredisk, do mbr cleaning
  	 skip_clean_mbr_opt="off"
           ;;
  esac
  
  if [ "$mode" = "restore" ]; then
    if [ "$ocs_user_mode" = "expert" ]; then
      # The option "-j2" (clone_hidden_data) should be only enabled by default when it's restoredisk
      # Ref: https://sourceforge.net/p/clonezilla/bugs/361/
      case "$dev_" in 
        parts) # For restoreparts
	       j2_switch_msg_1=""
	       j2_switch_msg_2=""
	       j2_switch_msg_3=""
	       ;;
        disk)  # For restoredisk
	       j2_switch_msg_1="-j2"
	       j2_switch_msg_2="$(rep_whspc_w_udrsc "$msg_ocs_param_j2")"
	       j2_switch_msg_3="on"
	       ;;
      esac
      $DIA --separate-output --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --checklist "$msg_choose_param_to_set_multiple_choices ($msg_press_space_to_mark_selection)" \
      0 0 0 $DIA_ESC \
      "-g auto"  "$msg_ocs_param_g_auto" $inst_grub_opt \
      "-e1 auto" "$msg_ocs_param_e1_auto" on \
      "-e2"      "$msg_ocs_param_e2" on \
      "-x"       "$msg_ocs_param_x" on \
      "-nogui"   "$msg_ocs_param_nogui" off \
      "-hn0 $WIN_HOSTNAME_PREFIX"  "$msg_ocs_param_hn0" off \
      "-hn1 $WIN_HOSTNAME_PREFIX"  "$msg_ocs_param_hn1" off \
      "-v"       "$msg_ocs_param_v" off \
      "-c"       "$msg_ocs_param_c" off \
      "-u"       "$msg_ocs_param_u" off \
      "-t"       "$msg_ocs_param_t" $skip_clean_mbr_opt \
      "-t1"      "$msg_ocs_param_t1" off \
      "-t2"      "$msg_ocs_param_t2" off \
      "-r"       "$msg_ocs_param_r" off \
      "-ns"      "$msg_ocs_param_ns" off \
      "-e"       "$msg_ocs_param_e" off \
      "-icrc"    "$msg_ocs_param_icrc" off \
      "-irhr"    "$msg_ocs_param_irhr" off \
      "-irvd"    "$msg_ocs_param_irvd" off \
      "-ius"     "$msg_ocs_param_ius" off \
      "-iui"     "$msg_ocs_param_iui" off \
      "-icds"    "$msg_ocs_param_icds" off \
      "-iefi"    "$msg_ocs_param_iefi" off \
      "-j1"      "$msg_ocs_param_j1" off \
      $j2_switch_msg_1 $j2_switch_msg_2 $j2_switch_msg_3 \
      "-cm"      "$msg_ocs_param_cm" off \
      "-cs"      "$msg_ocs_param_cs" off \
      "-cb2"     "$msg_ocs_param_cb2" off \
      "-cb3"     "$msg_ocs_param_cb3" off \
      "-cmf"     "$msg_ocs_param_cmf" off \
      "-f"       "$msg_ocs_param_f" off \
      "-rescue " "$msg_ocs_param_rescue" off \
      "-s"       "$msg_ocs_param_s" off \
      "-a"       "$msg_ocs_param_a" off \
      "-o0"      "$msg_ocs_param_o0" off \
      "-o1"      "$msg_ocs_param_o1" off \
      "-srel"    "$msg_ocs_param_srel" off \
      "-ssnf"    "$msg_ocs_param_ssnf" off \
      "-ps"      "$msg_ocs_param_ps" off \
      "-edio"    "$msg_ocs_param_edio" on \
      "-rmtd"    "$msg_ocs_param_rmtd" off \
      "-rmmcb"   "$msg_ocs_param_rmmcb" off \
      "-reluks"  "$msg_ocs_param_reluks" off \
    2>> $OCS_PARAM_TMP
    else
      # Beginner mode. Use default settings
      if [ "$inst_grub_opt" = "on" ]; then
        # restoredisk mode.
        # "$inst_grub_opt" = "on" (-g auto) means skip_clean_mbr_opt="off" (no -t)
        echo "-g auto" "-e1 auto" "-e2" "-r" "-x" "-j2" "-edio" >> $OCS_PARAM_TMP
      else
        # restoreparts mode.
        # "$inst_grub_opt" = "off" (no "-g auto") means skip_clean_mbr_opt="on" (-t)
        # Do not enable -j2 by default since for restoreparts, it should not be done by default.
        # Ref: https://sourceforge.net/p/clonezilla/bugs/361/
        echo "-e1 auto" "-e2" "-t" "-r" "-x" "-edio" >> $OCS_PARAM_TMP
      fi
    fi
  
    # About partition table
    case "$dev_" in 
    parts)
      # Partition restore only. default NOT to create partition table
      if [ "$ocs_user_mode" = "expert" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk \n$msg_choose_param_to_set_single_choice" \
        0 0 0 $DIA_ESC \
        "-k "      "$msg_ocs_param_k"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "-k2 "     "$msg_ocs_param_k2"  \
        "-j0 "     "$msg_ocs_param_j0" \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      else
        echo "-k " >> $OCS_PARAM_TMP
      fi
      ;;
    *)
      # Disk restore, default to create partition table
      if [ "$ocs_user_mode" = "expert" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk \n$msg_choose_param_to_set_single_choice" \
        0 0 0 $DIA_ESC \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "-k "      "$msg_ocs_param_k"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "-k2 "     "$msg_ocs_param_k2"  \
        "-j0 "     "$msg_ocs_param_j0" \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      else
        # Beginner mode.
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk_beginner \n$msg_choose_default_param_if_no_idea" \
        0 0 0 $DIA_ESC \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      fi
      ;;
    esac
    if grep -Ew "exit" $OCS_PARAM_TMP &>/dev/null; then
      echo "$msg_program_stop"
      exit 1
    fi
    # Question about checking the image is restorable or not. By default, no matter it's beginner or advanced mode, 
    # we will ask.
    if [ -z "$chk_img_restoreable_on_srv" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_checking_image_restorable_before_restoring_on_this_server" \
      0 0 0 $DIA_ESC \
      " "     "$msg_ocs_param_check_img_restorable_before_restoring" \
      "-sc0 " "$msg_ocs_param_skip_checking_img_restorable_before_restoring" \
      2>> $OCS_PARAM_TMP
    else
      echo " " >> $OCS_PARAM_TMP
    fi
    if LC_ALL=C grep -Ew -- "(-k1|-k2)" $OCS_PARAM_TMP &>/dev/null; then
      # Option -k1 or -k2 is for different partition size, turn on -r and -icds by default
      if [ -z "$(LC_ALL=C grep -Ew -- "-r" $OCS_PARAM_TMP)" ]; then
        echo "Since the mode you choose might resize partition size, we turn on file system resize funtion automatically (-r)..."
        echo "-r " >> $OCS_PARAM_TMP
      fi
      if [ -z "$(LC_ALL=C grep -Ew -- "-icds" $OCS_PARAM_TMP)" ]; then
        echo "Since the mode you choose might resize partition size, we now enable option \"-icds\" to ignore the partition size checking in Partclone..."
        echo "-icds ">> $OCS_PARAM_TMP
      fi
    fi
  
    # about y[0-2]
    if [ "$set_y_opt" = "yes" ]; then
      if [ "$ocs_user_mode" = "expert" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_if_always_provide_clonezilla_srv" \
        0 0 0 $DIA_ESC \
        " "         "$msg_ocs_param_skip" \
        "-y0 "      "$msg_ocs_param_y0" \
        "-y1 "      "$msg_ocs_param_y1" \
        "-y2 "      "$msg_ocs_param_y2" \
        2>> $OCS_PARAM_TMP
      else
        echo " " >> $OCS_PARAM_TMP
      fi
    fi
  else
    # Save mode.
    # about -q, -q1, -q2
    if [ "$ocs_user_mode" = "expert" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_param_for_clone_prog" \
      0 0 0 $DIA_ESC \
      "-q2 "       "$msg_ocs_param_q2" \
      "-q1 "       "$msg_ocs_param_q1" \
      "-q "        "$msg_ocs_param_q" \
      " "          "$msg_ocs_param_none_ie_partimage" \
      2>> $OCS_PARAM_TMP
    else
      echo "-q2 " >> $OCS_PARAM_TMP
    fi
  
    get_smtd_smmcb_switch  # Obtain smtd_smmcb_switch
    if [ "$ocs_user_mode" = "expert" ]; then
      $DIA --separate-output --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --checklist "$msg_choose_param_to_set_multiple_choices ($msg_press_space_to_mark_selection):" \
      0 0 0 $DIA_ESC \
      "-c "        "$msg_ocs_param_c" off \
      "-j2 "       "$msg_ocs_param_j2" on \
      "-nogui "    "$msg_ocs_param_nogui" off \
      "-a "        "$msg_ocs_param_a" off \
      "-batch "    "$msg_ocs_param_b" off \
      "-f "        "$msg_ocs_param_f" off \
      "-s "        "$msg_ocs_param_s" off \
      "-rm-win-swap-hib " "$msg_ocs_param_rm_win_swap_hib" off \
      "-ntfs-ok "  "$msg_ocs_param_ntfs_ok" off \
      "-rescue "   "$msg_ocs_param_rescue" off \
      "-gm "       "$msg_ocs_param_gm" off \
      "-gs "       "$msg_ocs_param_gs" off \
      "-gb2 "      "$msg_ocs_param_gb2" off \
      "-gb3 "      "$msg_ocs_param_gb3" off \
      "-gmf "      "$msg_ocs_param_gmf" off \
      "-noabo "    "$msg_ocs_param_noabo" off \
      "-o0 "       "$msg_ocs_param_o0" off \
      "-o1 "       "$msg_ocs_param_o1" off \
      "-ps "       "$msg_ocs_param_ps" off \
      "-scpt "     "$msg_ocs_param_scpt" off \
      "-sfs "      "$msg_ocs_param_sfs" off \
      "-edio "     "$msg_ocs_param_edio" on \
      "-smtd "     "$msg_ocs_param_smtd" $smtd_smmcb_switch \
      "-smmcb "    "$msg_ocs_param_smmcb" $smtd_smmcb_switch \
      2>> $OCS_PARAM_TMP
    else
      case "$smtd_smmcb_switch" in
         on) echo "-j2 " "-edio " "-smtd " "-smmcb " >> $OCS_PARAM_TMP;;
        off) echo "-j2 " "-edio " >> $OCS_PARAM_TMP;;
      esac
    fi
    # Question about fsck the source partition. By default, no matter it's beginner or advanced mode, we will ask.
    if [ -z "$fsck_src_part_intr" -a -z "$fsck_src_part_auto" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_fsck_the_source_part" \
      0 0 0 $DIA_ESC \
      " "     "$msg_skip_check_source_fs" \
      "-fsck "   "$msg_ocs_param_fsck_src_part" \
      "-fsck-y " "$msg_ocs_param_fsck_src_part_yes" \
      2>> $OCS_PARAM_TMP
    else
      case "$fsck_src_part_intr" in
        yes) echo "-fsck " >> $OCS_PARAM_TMP;;
          *) echo " " >> $OCS_PARAM_TMP;;
      esac
      case "$fsck_src_part_auto" in
        yes) echo "-fsck-y " >> $OCS_PARAM_TMP;;
          *) echo " " >> $OCS_PARAM_TMP;;
      esac
    fi
  
    # Question about checking the image is restorable or not. By default, no matter it's beginner or advanced mode, 
    # we will ask.
    if [ -z "$chk_img_restoreable_mod_save" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_checking_image_restorable" \
      0 0 0 $DIA_ESC \
      " "     "$msg_ocs_param_check_img_restorable" \
      "-scs " "$msg_ocs_param_skip_checking_img_restorable" \
      2>> $OCS_PARAM_TMP
    else
      case "$chk_img_restoreable_mod_save" in
        yes) echo " " >> $OCS_PARAM_TMP;;
         no) echo "-scs " >> $OCS_PARAM_TMP;;
      esac
    fi
  fi
  
  if [ -n "$default_postaction" ]; then
    postaction_opt="-d $default_postaction"
  fi
  ocs_advanced_param_post_mode_after_clone $postaction_opt $OCS_PARAM_TMP
  
  # if -hn0|-hn1 is chosen, 
  # (1). prompt the warning about ntfs-3g/nfsmount for ntfs is necessary
  # (2). ask if the hostname prefix want to change
  if grep -qE "\-hn[01]" $OCS_PARAM_TMP; then
    # part 1.
    $DIA --title "$msg_change_hostname_of_MS_WIN_on_the_fly" --clear \
         --msgbox "$msg_write_MS_WIN_is_necessary" 15 70
  
    # part 2.
    HNTMP="$(mktemp /tmp/winhn.XXXXXX)"
    $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla" \
    --inputbox "$msg_What_the_win_hostname_prefix ?" 0 0 "$WIN_HOSTNAME_PREFIX" 2> $HNTMP
    HN_PREFIX="$(cat $HNTMP)"
    if [ -z "$HN_PREFIX" ]; then
       echo "You did not specify the hostname prefix for MS windows! We use the default value in drbl-ocs.conf"
    else
       perl -pi -e "s|(-hn.*) $WIN_HOSTNAME_PREFIX|\$1 $HN_PREFIX|g" $OCS_PARAM_TMP
    fi
    [ -f "$HNTMP" ] && rm -f $HNTMP
  fi
  
  if [ "$mode" = "save" ]; then
    # Save mode.
    show_z4_or_above_menu_or_not
    # We can not detect # of the CPU cores in the clients from server, hence let user choose.
    if [ "$ocs_user_mode" = "expert" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
      --default-item "$ocs_z9p_option_1" \
      0 0 0 $DIA_ESC \
      "-z1p"     "$msg_ocs_param_z1p" \
      "-z1"      "$msg_ocs_param_z1" \
      "-z2p"     "$msg_ocs_param_z2p" \
      "-z2"      "$msg_ocs_param_z2" \
      "-z3"      "$msg_ocs_param_z3" \
      $ocs_z4_option_1      $ocs_z4_option_2 \
      $ocs_z5p_option_1     $ocs_z5p_option_2 \
      $ocs_z5_option_1      $ocs_z5_option_2 \
      $ocs_z6p_option_1     $ocs_z6p_option_2 \
      $ocs_z6_option_1      $ocs_z6_option_2 \
      $ocs_z7_option_1      $ocs_z7_option_2 \
      $ocs_z8_option_1      $ocs_z8_option_2 \
      $ocs_z8p_option_1     $ocs_z8p_option_2 \
      $ocs_z9_option_1      $ocs_z9_option_2 \
      $ocs_z9p_option_1     $ocs_z9p_option_2 \
      "-z0"      "$msg_ocs_param_z0" \
      2>> $OCS_PARAM_TMP
      # We need to append a space after this parameter so it won't be connected to next parameter.
      echo -n " " >> $OCS_PARAM_TMP
    else
      # Beginner mode. Question about -z1p and -z9p.
      # We can not detect # of the CPU cores in the clients from server, hence let user choose.
      # Here to make it simple, just use z*p since it works for both single and multiple cores.
      if [ -n "$ocs_z9p_option_1" -a -n "$ocs_z9p_option_2" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
	--default-item "$ocs_z9p_option_1" \
        0 0 0 $DIA_ESC \
        "-z1p"              "$msg_ocs_param_z1p" \
        $ocs_z9p_option_1   $ocs_z9p_option_2 \
        2>> $OCS_PARAM_TMP
        # We need to append a space after this parameter so it won't be connected to next parameter.
        echo -n " " >> $OCS_PARAM_TMP
      else
        echo "-z1p " >> $OCS_PARAM_TMP
      fi
    fi
    # About image volume size
    if [ -z "$dcs_img_vol_limit" ]; then
      trap "[ -f "$vol_size_tmp" ] && rm -f $vol_size_tmp" HUP INT QUIT TERM EXIT
      while [ "$ASK_VOL_SIZE" -ne 0 ]; do
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --inputbox "$msg_set_image_volume_size" \
        0 0 $VOL_LIMIT_DEFAULT \
        2> $vol_size_tmp
        if [ -n "$(cat $vol_size_tmp | grep -iE "[^[:digit:]]")" ]; then
          ASK_VOL_SIZE=1
          $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" \
          --msgbox "$msg_enter_digits_only\n$msg_please_do_it_again!!!" 0 0 
        else
          ASK_VOL_SIZE=0
        fi
      done
      echo "-i $(cat $vol_size_tmp)" >> $OCS_PARAM_TMP
    else
      echo "-i $dcs_img_vol_limit" >> $OCS_PARAM_TMP
    fi
  fi
  # Force to strip the unnecessary quotation ', this is specially for dialog (from cdialog) in Mandriva and same reason to strip the unnecessary double quotation ", this is sepcially for dialog in OpenSuSE 11.1. Otherwise it will cause -p reboot become (containing space) '-p reboot', which is wrong option in dcs.
  LC_ALL=C perl -pi -e "s/\'//g" $OCS_PARAM_TMP
  LC_ALL=C perl -pi -e "s/\"//g" $OCS_PARAM_TMP
  #
  [ -e "$vol_size_tmp" ] && rm -f $vol_size_tmp
} # end of set_drbl_ocs_extra_param

#
set_ocs_sr_extra_param() {
# This function is used to be called inside ocs-sr, not from other program.
local mode="$1"
# OCS_PARAM_TMP is a global variable
local mode2_="$2"
local cpu_no
local vol_size_tmp
local ASK_VOL_SIZE=1
local inst_grub_opt opt_confirm_ j2_switch_msg_1 j2_switch_msg_2 j2_switch_msg_3
vol_size_tmp="$(mktemp /tmp/vol_size_tmp.XXXXXX)"

if [ -z "$OCS_PARAM_TMP" ]; then
  echo "\"$OCS_PARAM_TMP\" was not assigned in function set_ocs_sr_extra_param"
  echo "$msg_program_stop!"
  exit 1
fi

if [ "$mode2_" = "recovery-iso-zip" ]; then
  # E.g., set_ocs_sr_extra_param restore /tmp/ocs_recovery_tmp.8YNkii recovery-iso-zip
  # When mode2_ is recovery-iso-zip, we have to convert it to restoreparts or restoredisk
  # by testing the image
  if [ -e "$ocsroot/$target_dir/disk" ]; then
    mode2_="restoredisk"
  else
    mode2_="restoreparts"
  fi
fi

# If the mode is only for parts, we won't turn on "-g auto" option by default
case "$mode2_" in
  *parts) inst_grub_opt="off"
	  # For restoreparts, forget about clean mbr
	  skip_clean_mbr_opt="on"
	  ;;
       *) inst_grub_opt="on"
	  # For restoredisk, do mbr cleaning
	  skip_clean_mbr_opt="off"
	  ;;
esac

if [ "$mode" = "restore" ]; then
  # Although -u/-y0/-y1 is shown in ocs-sr, but actually they are used to
  # pass the varialbe, and in this function, when chooing parameters, we
  # remove them on purpose. Since the necessay parameters will be assigned by
  # drbl-ocs (Ex: we use "-y1 -p choose" in drbl-ocs)
  if [ "$ocs_user_mode" = "expert" ]; then
    # The option "-j2" (clone_hidden_data) should be only shown when it's in restoredisk mode
    # Ref: https://sourceforge.net/p/clonezilla/bugs/361/
    case "$mode2_" in 
      restoreparts) 
	      j2_switch_msg_1="-j2"
	      j2_switch_msg_2="$(rep_whspc_w_udrsc "$msg_ocs_param_j2")"
	      j2_switch_msg_3="off"
	      ;;
      restoredisk)
	      j2_switch_msg_1="-j2"
	      j2_switch_msg_2="$(rep_whspc_w_udrsc "$msg_ocs_param_j2")"
	      j2_switch_msg_3="on"
	      ;;
    esac
    $DIA --separate-output --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --checklist "$msg_choose_param_to_set_multiple_choices ($msg_press_space_to_mark_selection)" \
    0 0 0 $DIA_ESC \
    "-g auto"  "$msg_ocs_param_g_auto" $inst_grub_opt \
    "-e1 auto" "$msg_ocs_param_e1_auto" on \
    "-e2"      "$msg_ocs_param_e2" on \
    "-nogui"   "$msg_ocs_param_nogui" off \
    "-hn0 $WIN_HOSTNAME_PREFIX"  "$msg_ocs_param_hn0" off \
    "-hn1 $WIN_HOSTNAME_PREFIX"  "$msg_ocs_param_hn1" off \
    "-v"       "$msg_ocs_param_v" off \
    "-batch"   "$msg_ocs_param_b" off \
    "-c"       "$msg_ocs_param_c" on \
    "-t"       "$msg_ocs_param_t" $skip_clean_mbr_opt \
    "-t1"      "$msg_ocs_param_t1" off \
    "-t2"      "$msg_ocs_param_t2" off \
    "-r"       "$msg_ocs_param_r" off \
    "-rescue " "$msg_ocs_param_rescue" off \
    "-e"       "$msg_ocs_param_e" off \
    "-icrc"    "$msg_ocs_param_icrc" off \
    "-irhr"    "$msg_ocs_param_irhr" off \
    "-irvd"    "$msg_ocs_param_irvd" off \
    "-ius"     "$msg_ocs_param_ius" off \
    "-iui"     "$msg_ocs_param_iui" off \
    "-icds"    "$msg_ocs_param_icds" off \
    "-iefi"    "$msg_ocs_param_iefi" off \
    "-j1"      "$msg_ocs_param_j1" off \
    $j2_switch_msg_1 $j2_switch_msg_2 $j2_switch_msg_3 \
    "-cm"      "$msg_ocs_param_cm" off \
    "-cs"      "$msg_ocs_param_cs" off \
    "-cb2"      "$msg_ocs_param_cb2" off \
    "-cb3"      "$msg_ocs_param_cb3" off \
    "-cmf"     "$msg_ocs_param_cmf" off \
    "-a"       "$msg_ocs_param_a" off \
    "-o0"      "$msg_ocs_param_o0" off \
    "-o1"      "$msg_ocs_param_o1" off \
    "-srel"    "$msg_ocs_param_srel" off \
    "-ps"      "$msg_ocs_param_ps" off \
    "-edio"    "$msg_ocs_param_edio" on \
    "-rmtd"    "$msg_ocs_param_rmtd" off \
    "-rmmcb"   "$msg_ocs_param_rmmcb" off \
    "-reluks"  "$msg_ocs_param_reluks" off \
    2>> $OCS_PARAM_TMP
  else
    if [ "$ocs_batch_mode" != "on" ]; then
      # Interactive mode. We need to add "-c"
      opt_confirm_="-c"
    else
      # Batch mode. We do not add "-c"
      opt_confirm_=""
    fi
    # Beginner mode. Use default settings
    if [ "$inst_grub_opt" = "on" ]; then
      # restoredisk mode.
      # "$inst_grub_opt" = "on" (-g auto) means skip_clean_mbr_opt="off" (no -t)
      echo "-g auto" "-e1 auto" "-e2" "-r" "-j2" "-edio" "$opt_confirm_" >> $OCS_PARAM_TMP
    else
      # restoreparts mode.
      # "$inst_grub_opt" = "off" (no "-g auto") means skip_clean_mbr_opt="on" (-t)
      # Do not enable -j2 by default since for restoreparts, it should not be done by default.
      # Ref: https://sourceforge.net/p/clonezilla/bugs/361/
      echo "-e1 auto" "-e2" "-t" "-r" "-edio" "$opt_confirm_" >> $OCS_PARAM_TMP
    fi
  fi

  # About partition table
  case "$mode2_" in 
    "restoreparts") 
      # Partition restore only. default NOT to create partition table
      if [ "$ocs_user_mode" = "expert" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk \n$msg_choose_param_to_set_single_choice" \
        0 0 0 $DIA_ESC \
        "-k "      "$msg_ocs_param_k"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "-k2 "     "$msg_ocs_param_k2"  \
        "-j0 "     "$msg_ocs_param_j0" \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      else
        echo "-k " >> $OCS_PARAM_TMP
      fi
      ;;
    *)
      # Disk restore, default to create partition table
      if [ "$ocs_user_mode" = "expert" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk \n$msg_choose_param_to_set_single_choice" \
        0 0 0 $DIA_ESC \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "-k "      "$msg_ocs_param_k"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "-k2 "     "$msg_ocs_param_k2"  \
        "-j0 "     "$msg_ocs_param_j0" \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      else
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_hint_for_fdisk_beginner \n$msg_choose_default_param_if_no_idea" \
        0 0 0 $DIA_ESC \
        "-k0 "     "$msg_use_the_part_table_from_image"  \
        "-k1 "     "$msg_ocs_param_k1"  \
        "exit "    "$msg_exit" \
        2>> $OCS_PARAM_TMP
      fi
      ;;
  esac
  if grep -Ew "exit" $OCS_PARAM_TMP &>/dev/null; then
    echo "$msg_program_stop"
    exit 1
  fi
  # Question about checking the image is restorable or not. By default, no matter it's beginner or advanced mode, 
  # we will ask.
  if [ -z "$chk_img_restoreable_mod_restore" ]; then
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_checking_image_restorable_before_restoring" \
    0 0 0 $DIA_ESC \
    " "     "$msg_ocs_param_check_img_restorable_before_restoring" \
    "-scr " "$msg_ocs_param_skip_checking_img_restorable_before_restoring" \
    2>> $OCS_PARAM_TMP
  else
    case "$chk_img_restoreable_mod_restore" in
      yes) echo " " >> $OCS_PARAM_TMP;;
       no) echo "-scr " >> $OCS_PARAM_TMP;;
    esac
  fi
  if LC_ALL=C grep -Ew -- "(-k1|-k2)" $OCS_PARAM_TMP &>/dev/null; then
    # Option -k1 or -k2 is for different partition size, turn on -r and -icds by default
    if [ -z "$(LC_ALL=C grep -Ew -- "-r" $OCS_PARAM_TMP)" ]; then
      echo "Since the mode you choose might resize partition size, we turn on file system resize funtion automatically (-r)..."
      echo "-r " >> $OCS_PARAM_TMP
    fi
    if [ -z "$(LC_ALL=C grep -Ew -- "-icds" $OCS_PARAM_TMP)" ]; then
      echo "Since the mode you choose might resize partition size, we now enable option \"-icds\" to ignore the partition size checking in Partclone..."
      echo "-icds " >> $OCS_PARAM_TMP
    fi
  fi
else
  # Save mode.
  # about -q, -q1, -q2
  if [ "$ocs_user_mode" = "expert" ]; then
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_param_for_clone_prog" \
    0 0 0 $DIA_ESC \
    "-q2 "       "$msg_ocs_param_q2" \
    "-q1 "       "$msg_ocs_param_q1" \
    "-q "        "$msg_ocs_param_q" \
    " "          "$msg_ocs_param_none_ie_partimage" \
    2>> $OCS_PARAM_TMP
  else
    echo "-q2 " >> $OCS_PARAM_TMP
  fi

  get_smtd_smmcb_switch  # Obtain smtd_smmcb_switch
  if [ "$ocs_user_mode" = "expert" ]; then
    $DIA --separate-output --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --checklist "$msg_choose_param_to_set_multiple_choices ($msg_press_space_to_mark_selection):" \
    0 0 0 $DIA_ESC \
    "-c "       "$msg_ocs_param_c" on \
    "-j2 "      "$msg_ocs_param_j2" on \
    "-nogui "   "$msg_ocs_param_nogui" off \
    "-a "       "$msg_ocs_param_a" off \
    "-batch "    "$msg_ocs_param_b" off \
    "-rm-win-swap-hib " "$msg_ocs_param_rm_win_swap_hib" off \
    "-ntfs-ok " "$msg_ocs_param_ntfs_ok" off \
    "-rescue "  "$msg_ocs_param_rescue" off \
    "-gm "      "$msg_ocs_param_gm" off \
    "-gs "      "$msg_ocs_param_gs" off \
    "-gb2 "     "$msg_ocs_param_gb2" off \
    "-gb3 "     "$msg_ocs_param_gb3" off \
    "-gmf "     "$msg_ocs_param_gmf" off \
    "-noabo "   "$msg_ocs_param_noabo" off \
    "-ps "      "$msg_ocs_param_ps" off \
    "-scpt "    "$msg_ocs_param_scpt" off \
    "-sfs "     "$msg_ocs_param_sfs" off \
    "-edio "    "$msg_ocs_param_edio" on \
    "-smtd "    "$msg_ocs_param_smtd" $smtd_smmcb_switch \
    "-smmcb "   "$msg_ocs_param_smmcb" $smtd_smmcb_switch \
    2>> $OCS_PARAM_TMP
  else
      case "$smtd_smmcb_switch" in
         on) echo "-c " "-j2 " "-edio " "-smtd " "-smmcb " >> $OCS_PARAM_TMP;;
        off) echo "-c " "-j2 " "-edio " >> $OCS_PARAM_TMP;;
      esac
  fi
fi

# if -hn0|-hn1 is chosen, 
# (1). prompt the warning about ntfs-3g/nfsmount for ntfs is necessary
# (2). ask if the hostname prefix want to change
if grep -qE "\-hn[01]" $OCS_PARAM_TMP; then
  # part 1.
  $DIA --title "$msg_change_hostname_of_MS_WIN_on_the_fly" --clear \
       --msgbox "$msg_write_MS_WIN_is_necessary" 15 70

  # part 2.
  HNTMP="$(mktemp /tmp/winhn.XXXXXX)"
  $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla" \
  --inputbox "$msg_What_the_win_hostname_prefix ?" 0 0 "$WIN_HOSTNAME_PREFIX" 2> $HNTMP
  HN_PREFIX="$(cat $HNTMP)"
  if [ -z "$HN_PREFIX" ]; then
     echo "You did not specify the hostname prefix for MS windows! We use the default value in drbl-ocs.conf"
  else
     perl -pi -e "s|(-hn.*) $WIN_HOSTNAME_PREFIX|\$1 $HN_PREFIX|g" $OCS_PARAM_TMP
  fi
  [ -f "$HNTMP" ] && rm -f $HNTMP
fi

if [ "$mode" = "save" ]; then
  cpu_no="$(LC_ALL=C grep -iE "^processor" /proc/cpuinfo | wc -l)" 
  # Due to the extra space required after -z1p, we can NOT use variable like this:
  # if [ "$cpu_no" -gt 1 ]; then
  #   z1p_option_1="-z1p "
  #   z1p_option_2="$msg_ocs_param_z1p"
  # else
  #   z1p_option_1=""
  #   z1p_option_2=""
  # fi
  # $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
  # "$msg_clonezilla_advanced_extra_param" --menu "$msg_choose_one_compression_param_to_save" \
  # 0 0 0 $DIA_ESC \
  # "-z1 "            "$msg_ocs_param_z1" \
  # $z1p_option_1     $z1p_option_2 \
  # "-z2 "            "$msg_ocs_param_z2" \
  # "-z3 "            "$msg_ocs_param_z3" \
  # "-z0 "            "$msg_ocs_param_z0" \
  # 2>> $OCS_PARAM_TMP
  show_z4_or_above_menu_or_not
  if [ "$cpu_no" -gt 1 ]; then
    # Show -z1p
    if [ "$ocs_user_mode" = "expert" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
      --default-item "$ocs_z9p_option_1" \
      0 0 0 $DIA_ESC \
      "-z1p"           "$msg_ocs_param_z1p" \
      "-z1"            "$msg_ocs_param_z1" \
      "-z2p"           "$msg_ocs_param_z2p" \
      "-z2"            "$msg_ocs_param_z2" \
      "-z3"            "$msg_ocs_param_z3" \
      $ocs_z4_option_1  $ocs_z4_option_2 \
      $ocs_z5p_option_1 $ocs_z5p_option_2 \
      $ocs_z5_option_1  $ocs_z5_option_2 \
      $ocs_z6p_option_1 $ocs_z6p_option_2 \
      $ocs_z6_option_1  $ocs_z6_option_2 \
      $ocs_z7_option_1  $ocs_z7_option_2 \
      $ocs_z8_option_1  $ocs_z8_option_2 \
      $ocs_z8p_option_1 $ocs_z8p_option_2 \
      $ocs_z9_option_1  $ocs_z9_option_2 \
      $ocs_z9p_option_1 $ocs_z9p_option_2 \
      "-z0"            "$msg_ocs_param_z0" \
      2>> $OCS_PARAM_TMP
      # We need to append a space after this parameter so it won't be connected to next parameter.
      echo -n " " >> $OCS_PARAM_TMP
    else
      # Beginner mode.
      # Question about -z1p and -z9p.
      if [ -n "$ocs_z9p_option_1" -a -n "$ocs_z9p_option_2" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
	--default-item "$ocs_z9p_option_1" \
        0 0 0 $DIA_ESC \
        "-z1p"              "$msg_ocs_param_z1p" \
        $ocs_z9p_option_1   $ocs_z9p_option_2 \
        2>> $OCS_PARAM_TMP
        # We need to append a space after this parameter so it won't be connected to next parameter.
        echo -n " " >> $OCS_PARAM_TMP
      else
        echo "-z1p " >> $OCS_PARAM_TMP
      fi
    fi
  else
    # Single processor, so we hide -z1p, z2p...
    if [ "$ocs_user_mode" = "expert" ]; then
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
      0 0 0 $DIA_ESC \
      "-z1"            "$msg_ocs_param_z1" \
      "-z2"            "$msg_ocs_param_z2" \
      "-z3"            "$msg_ocs_param_z3" \
      $ocs_z4_option_1  $ocs_z4_option_2 \
      $ocs_z5_option_1  $ocs_z5_option_2 \
      $ocs_z6_option_1  $ocs_z6_option_2 \
      $ocs_z7_option_1  $ocs_z7_option_2 \
      $ocs_z8_option_1  $ocs_z8_option_2 \
      $ocs_z9_option_1  $ocs_z9_option_2 \
      "-z0"            "$msg_ocs_param_z0" \
      2>> $OCS_PARAM_TMP
      # We need to append a space after this parameter so it won't be connected to next parameter.
      echo -n " " >> $OCS_PARAM_TMP
    else
      # Beginner mode.
      # Question about -z1 and -z9.
      if [ -n "$ocs_z9_option_1" -a -n "$ocs_z9_option_2" ]; then
        $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
        "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_one_compression_param_to_save" \
	--default-item "$ocs_z9_option_1" \
        0 0 0 $DIA_ESC \
        "-z1"              "$msg_ocs_param_z1" \
        $ocs_z9_option_1   $ocs_z9_option_2 \
        2>> $OCS_PARAM_TMP
        # We need to append a space after this parameter so it won't be connected to next parameter.
        echo -n " " >> $OCS_PARAM_TMP
      else
        echo "-z1 " >> $OCS_PARAM_TMP
      fi
    fi
  fi

  # About image volume size
  if [ "$ocs_user_mode" = "expert" ]; then
    trap "[ -f "$vol_size_tmp" ] && rm -f $vol_size_tmp" HUP INT QUIT TERM EXIT
    while [ "$ASK_VOL_SIZE" -ne 0 ]; do
      $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
      "$msg_clonezilla_advanced_extra_param | $msg_mode: $ocs_mode_prompt" --inputbox "$msg_set_image_volume_size" \
      0 0 $VOL_LIMIT_IN_INTERACTIVE\
      2> $vol_size_tmp
      if [ -n "$(cat $vol_size_tmp | grep -iE "[^[:digit:]]")" ]; then
        ASK_VOL_SIZE=1
        $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" \
        --msgbox "$msg_enter_digits_only\n$msg_please_do_it_again!!!" 0 0 
      else
        ASK_VOL_SIZE=0
      fi
    done
    echo "-i $(cat $vol_size_tmp)" >> $OCS_PARAM_TMP
  else
    echo "-i $VOL_LIMIT_IN_INTERACTIVE" >> $OCS_PARAM_TMP
  fi
  # Question about fsck the source partition. By default, no matter it's beginner or advanced mode, we will ask.
  if [ -z "$fsck_src_part_intr" -a -z "$fsck_src_part_auto" ]; then
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_fsck_the_source_part" \
    0 0 0 $DIA_ESC \
    "-sfsck "  "$msg_skip_check_source_fs" \
    "-fsck "   "$msg_ocs_param_fsck_src_part" \
    "-fsck-y " "$msg_ocs_param_fsck_src_part_yes" \
    2>> $OCS_PARAM_TMP
  else
    case "$fsck_src_part_intr" in
      yes) echo "-fsck " >> $OCS_PARAM_TMP;;
        *) echo " " >> $OCS_PARAM_TMP;;
    esac
    case "$fsck_src_part_auto" in
      yes) echo "-fsck-y " >> $OCS_PARAM_TMP;;
        *) echo " " >> $OCS_PARAM_TMP;;
    esac
  fi
  
  # Question about checking the image is restorable or not. By default, no matter it's beginner or advanced mode, 
  # we will ask.
  if [ -z "$chk_img_restoreable_mod_save" ]; then
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_choose_if_checking_image_restorable" \
    0 0 0 $DIA_ESC \
    " "     "$msg_ocs_param_check_img_restorable" \
    "-scs " "$msg_ocs_param_skip_checking_img_restorable" \
    2>> $OCS_PARAM_TMP
  else
    case "$chk_img_restoreable_mod_save" in
      yes) echo " " >> $OCS_PARAM_TMP;;
       no) echo "-scs " >> $OCS_PARAM_TMP;;
    esac
  fi

  # Question about encrypt the image. By default, no matter it's beginner or advanced mode, 
  # we will ask. However, for some customized case, it it could be set via parameter encrypt_ocs_img.
  # encrypt_ocs_img is from /etc/ocs/ocs-live.conf
  if [ -z "$encrypt_ocs_img" ]; then
    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_encrypt_image\n$msg_ecryptfs_is_used_for_clonezilla\n$msg_remember_passphrase_of_ecryptfs" \
    0 0 0 $DIA_ESC \
    "-senc "    "$msg_not_to_encrypt_img" \
    "-enc "     "$msg_yes_to_encrypt_img" \
    2>> $OCS_PARAM_TMP
  else
    case "$encrypt_ocs_img" in
      yes) echo "-enc " >> $OCS_PARAM_TMP;;
       no) echo "-senc " >> $OCS_PARAM_TMP;;
    esac
  fi
fi

# Question about copy the log files to Clonezilla live USB drive. By default, no matter it's beginner or advanced mode, 
if [ -z "$put_log_usb" ]; then
  $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
  "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" --menu "$msg_put_log_usb_or_not \n$msg_choose_default_param_if_no_idea" \
  0 0 0 $DIA_ESC \
  "-plu "    "$msg_put_log_to_OCS_USB_drive" \
  " "        "$msg_not_put_log_to_OCS_USB_drive" \
  2>> $OCS_PARAM_TMP
else
  case "$put_log_usb" in
    yes) echo "-plu " >> $OCS_PARAM_TMP;;
     no) echo " " >> $OCS_PARAM_TMP;;
  esac
fi

# For both beginner and expert modes, if user has specified postaction, then we do not have to set it. Otherwise, ask it.
if [ -n "$postaction" ]; then
  echo "-p $postaction " >> $OCS_PARAM_TMP
else
  ocs_sr_param_postaction_after_clone $OCS_PARAM_TMP
fi

# Force to strip the unnecessary quotation ', this is specially for dialog (from cdialog) in Mandriva and same reason to strip the unnecessary double quotation ", this is sepcially for dialog in OpenSuSE 11.1. Otherwise it will cause -p reboot become (containing space) '-p reboot', which is wrong option in dcs.
LC_ALL=C perl -pi -e "s/\'//g" $OCS_PARAM_TMP
LC_ALL=C perl -pi -e "s/\"//g" $OCS_PARAM_TMP
#
[ -e "$vol_size_tmp" ] && rm -f $vol_size_tmp

} # end of set_ocs_sr_extra_param
#
check_DIA_set_ESC(){
  # function to check dialog/Xdialog/whiptail
  # DIA_ESC is global variable, 
  # man dialog:
  # A "--" by itself is used as an escape, i.e., the next token on the com-
  # mand-line is not treated as an option.
  # dialog --title -- --Not an option
  # 3 cases if those Not an option is like (-g auto, -x...):
  # (1) dialog can go with or without --
  # (2) Xdialog can NOT go with --
  # (3) whiptail can go only with --
  local dia_="$1"
  # check DIA
  if ! type $dia_ &>/dev/null; then
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "$dia_: command not found!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     echo "Program terminated!!!"
     exit 1
  fi
  case "$dia_" in
    dialog|[Xgk]dialog) DIA_ESC="" ;;
    whiptail) DIA_ESC="--" ;;
  esac
} # end of check_DIA_set_ESC
#
check_if_run_in_drbl_server() {
  local prog="$1"
  # check if it s run in drbl server
  if [ ! -d "$PXELINUX_DIR" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "[$LOGNAME] You should run this program $prog in DRBL server, NOT in DRBL client or other machine."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "Program terminated!"
    exit 1
  fi
}
dialog_like_prog_help_prompt() {
   echo " -d0, --dialog         Use dialog"
   echo " -d1, --Xdialog        Use Xdialog"
   echo " -d2, --whiptail       Use whiptail"
   echo " -d3, --gdialog        Use gdialog"
   echo " -d4, --kdialog        Use kdialog"
}
root_over_nfs() {
  local root_over_nfs
  root_over_nfs="$(grep -Ew "^[[:space:]]*([[:digit:]]+\.){3}[[:digit:]]+:/tftpboot/node_root([[:space:]]+|$)" /proc/mounts | awk -F " " '{print $2}')"
  if [ "$root_over_nfs" = "/" ]; then
    echo "yes"
    rc=0
  else
    echo "no"
    rc=1
  fi
  return $rc
}
#
make_random_password(){ 
  # Copyright (C) 2007 Bryan McLellan <btm@loftninjas.org>
  # Licensed under the GNU GPL version 2 or greater, see COPYING
  # generate a random password of length passed out of characters in array char. returns password in $random_password
  # replaces external perl password generation script
  # Modified by Steven Shiau, remove 0, 1, add [ ] ^ ! $ %
  local randchar=""
  [ -z "$1" ] && lenpass=6 || lenpass=$1

  # To avoid confusing, no 0, 1 for passwd, the O (oh) and l (L) will be clear. 
  char=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 2 3 4 5 6 7 8 9 \[ \] ^ ! \$ %)
  lenchars=${#char[*]}

  for (( x=0 ; x<${lenpass} ; x+=1 ));
  do
    let rand=${RANDOM}%${lenchars}
    randchar=${randchar}${char[$rand]}
  done

  random_password=${randchar}
}
#
is_boot_from_live() {
  # function to check if the running OS is boot from live cd/usb stick ?
  if [ -e /etc/debian_version -a \
       -n "$(grep -iEo "(boot=casper|boot=live)" /proc/cmdline)" ]; then
     return 0
  else
     return 1
  fi
}
#
ask_nic_dev() {
  # chosen_nics is a global variable
  local dia_type req_nic_no dia_prompt nic_tmp
  local nic_no dia_def_status NETDEVICES count hw_scan_tmp DEVICELIST dev_model link_status hwaddr DEVICELIST read_cache
  local enable_channel_bonding="no"
  # link_max_cache_sec is from drbl-ocs.conf
  # The file name prefix for link status file. It will be used like /tmp/linked-status.eth0
  # ocs_nic_type is a global variable
  local link_status_cache_pref="/tmp/linked-status"

  while [ $# -gt 0 ]; do
    case "$1" in
      -e|--enable-channel-bonding)
           enable_channel_bonding="yes"
           shift;;
      -*)  echo "${0}: ${1}: invalid option in ask_nic_dev." | tee --append ${OCS_LOGFILE} >&2
           echo "$msg_program_stop" | tee --append ${OCS_LOGFILE}
           [ "$save_restore_error_log" = "yes" ] && copy_error_log
           exit 2 ;;
       *)  break ;;
    esac
  done

  dia_prompt="$1"
  dia_type="$2"
  req_nic_no="$3"
  nic_tmp="$(mktemp /tmp/netbonding.XXXXXX)"
  trap "[ -f "$nic_tmp" ] && rm -f $nic_tmp" HUP INT QUIT TERM EXIT
  
  case "$dia_type" in
    menu)      dia_def_status="";;
    checklist) dia_def_status="on";;
  esac

  # ocs_nic_type is from:
  # (1) boot parameter, hence in /etc/ocs/ocs-live.conf
  # (2) assigned by ocs-live-netcfg
  case "$ocs_nic_type" in
    wired)
      NETDEVICES="$(grep -E "^[[:print:]]+:[[:space:]]+" /proc/net/dev | awk -F: '! /wlan.*:|wl.*:|lo:/{print $1}' | sort)"
      ;;
    wireless)
      NETDEVICES="$(awk -F: '/wlan.*:|wl.*:/{print $1}' /proc/net/dev | sort)"
      ;;
    *)
      echo "ocs_nic_type is not wired or wireless. No idea how to process."
      echo "$msg_program_stop!"
      my_ocs_exit 1
      ;;
  esac
  # make it in a single line
  NETDEVICES="$(echo $NETDEVICES)"
  nic_no="$(echo $NETDEVICES | wc -w)"
  if [ "$nic_no" -lt "$req_nic_no" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "The requested NIC number is: $req_nic_no, while the NIC number on this system is: $nic_no"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    show_nic_dev_status_on_system
    echo "$msg_program_stop!"
    my_ocs_exit 1
  fi
  # Check if it makes sense when channel bonding is enabled
  if [ "$enable_channel_bonding" = "yes" ]; then
    if [ "$nic_no" -lt 2 ]; then
      echo "Disable channnel bonding since there is only one NIC found."
      enable_channel_bonding="no"
    fi
  fi
  
  if [ -z "$NETDEVICES" ]; then
    $DIA --msgbox "$msg_no_nic_is_found" 0 0
    if [ -n "$nic_tmp" ]; then
      rm -f "$nic_tmp"
    fi
    exit 1
  else
    # We have to up the network card first so that ethtool can detect if it's linked or not.
    echo -n "Try to up "
    for DEVICE in $NETDEVICES; do
      if [ -z "$(drbl-get-ipadd $DEVICE)" ]; then
        echo -n "$DEVICE... "
	ip link set $DEVICE up
      fi
    done
    echo
  fi
  
  count="$(echo "$NETDEVICES" | wc -w)"
  
  if [ "$count" -gt 1 ]; then
    hw_scan_tmp="$(mktemp /tmp/hw_scan.XXXXXX)"
    time_now="$(LC_ALL=C date +%s)"
    # Read the cached linked status from file.
    if type lshw &>/dev/null; then
      echo -n "Collecting the info of network devices... "
      lshw -businfo -class network 2>/dev/null > $hw_scan_tmp
      echo "done!"
    fi
    DEVICELIST=""
    dev_model=""
    for DEVICE in $NETDEVICES; do
      dev_model="$(LC_ALL=C grep -Ew "$DEVICE" $hw_scan_tmp | sed -e "s/^.*$DEVICE[[:space:]]*network[[:space:]]*//g" | sed -e "s/ /_/g")"
      [ -z "$dev_model" ] && dev_model="Unknown_NIC"
      # only first 26 characters.
      dev_model="${dev_model:0:25}.."
      link_status=""
      read_cache=""
      if [ -e "${link_status_cache_pref}.${DEVICE}" ]; then
        time_status_file="$(LC_ALL=C stat -c %Z "${link_status_cache_pref}.${DEVICE}")"
	if [ "$((time_now - time_status_file))" -le "$link_max_cache_sec" ]; then
         read_cache="yes"
        fi
      fi
      if [ "$read_cache" = "yes" ]; then
        echo "Reading link status from cache file ${link_status_cache_pref}.${DEVICE}..."
        . ${link_status_cache_pref}.${DEVICE}
      else
	if [ -n "$(echo $DEVICE | grep -Ew "(^wl.*|^wlan.*)")" ]; then
          echo "$DEVICE is a wireless device. No need to detect its linking status."
        else
          echo -n "Getting the linking status of $DEVICE. Timeout in $ocs_netlink_timeout secs."
          TIMEOUT="$ocs_netlink_timeout"
          while [ "$link_status" = "no" -o -z "$link_status" ]; do
            sleep 1
            link_status="$(LC_ALL=C ethtool $DEVICE | grep -i "Link detected:" | cut -d":" -f2 | sed -e "s/ //g")"
            TIMEOUT="$(( $TIMEOUT - 1 ))"
            if [ "$TIMEOUT" -le 0 ]; then
              echo
              echo -n "Timeout when finding linking status of $DEVICE."
    	  sleep 2
              break
            else
              echo -n "."
            fi
          done
        fi
        if [ "$link_status" = "yes" ]; then
          echo " Found status \"linked\"."
        else
          echo " Status \"not linked\" or \"unknown\"."
        fi
        if [ -z "$link_status" ]; then
          link_status="Unknown"     
        fi
	echo "link_status=\"${link_status}\"" > ${link_status_cache_pref}.${DEVICE}
      fi
      hwaddr="$(drbl-get-macadd $DEVICE)"
      DEVICELIST="$DEVICELIST ${DEVICE} $(rep_whspc_w_udrsc "$msg_link_detected"):${link_status}(${dev_model}|${hwaddr}) $dia_def_status"
    done
    rm -f "$nic_tmp"
    [ -f "$hw_scan_tmp" -a -n "$hw_scan_tmp" ] && rm -f $hw_scan_tmp

    if [ "$enable_channel_bonding" = "yes" ]; then
      DEVICELIST="$DEVICELIST bond0 $(rep_whspc_w_udrsc "$msg_use_channel_bonding") $dia_def_status"
    fi

    $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
    "$msg_nchc_clonezilla" --${dia_type} "$dia_prompt" 0 0 0 $DEVICELIST 2>"$nic_tmp"
    # Force to strip the unnecessary quotation ', this is specially for dialog (from cdialog) in Mandriva and same reason to strip the unnecessary double quotation ", this is sepcially for dialog in OpenSuSE 11.1. Otherwise it will cause -p reboot become (containing space) '-p reboot', which is wrong option in dcs.
    LC_ALL=C perl -pi -e "s/\'//g" $nic_tmp
    LC_ALL=C perl -pi -e "s/\"//g" $nic_tmp
    chosen_nics="$(cat $nic_tmp)"
  else
    # Only 1 NIC, just use it.
    # Remove additional spaces
    chosen_nics="$(echo $NETDEVICES)"
  fi
  
  if [ -n "$nic_tmp" ]; then
    rm -f "$nic_tmp"
  fi
} # end of ask_nic_dev
#
detect_dhcp_srv_in_lan() {
  # Return global variable "use_existing_dhcp_srv", "DHCPOFFER_eth", "DHCPOFFER_siaddr",
  # "DHCPOFFER_yiaddr", "DHCPOFFER_netmask", "DHCPOFFER_prefix"
  local nic_n eth_pt dhcp_detect_bond_tmp dhcp_find_rc
  nic_n="$(LC_ALL=C get-nic-devs | wc -l)"
  if [ "$nic_n" -eq 0 ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "No any ethernet card found!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop"
    exit 1
  elif [ "$nic_n" -eq 1 ]; then
    eth_pt="$(LC_ALL=C get-nic-devs)"
  else
    # Multiple NICs, let user choose
    [ -z "$ocs_nic_type" ] && ocs_nic_type="wired"
    [ -z "$ocs_netlink_timeout" ] && ocs_netlink_timeout="12"
    ask_nic_dev -e "$msg_choose_nic?" menu 1 # Obtain $chosen_nics
    if [ -n "$chosen_nics" ]; then
      echo "Chosen NIC: $chosen_nics"
      eth_pt="$chosen_nics"
    fi
  fi
  dhcp_detect_bond_tmp="$(mktemp /tmp/dhcp_detect_bond_tmp.XXXXXX)"
  dhcp_find_rc=1
  echo "Trying to find if existing DHCP service available on local network via ${eth_pt}..."
  while [ "$dhcp_find_rc" -ne 0 ]; do
    drbl-find-dhcp-srv -i $eth_pt $dhcp_detect_bond_tmp
    dhcp_find_rc=$?
    if [ "$dhcp_find_rc" -ne 0 ]; then
      echo
      echo "$msg_failed_to_find_any_dhcp_srv: $eth_pt"
      echo "$msg_do_u_want_to_do_it_again"
      echo -n "[Y/n] "
      read try_dhcp_again
      case "$try_dhcp_again" in
        n|N|[nN][oO])
           echo "$msg_program_stop"
           dhcp_find_rc=0
           ;;
        *)
           echo "$msg_ok_let_do_it"
           dhcp_find_rc=1
           ;;
      esac
    fi
  done
  . $dhcp_detect_bond_tmp
  # Example for file dhcp_detect_bond_tmp:
  # DHCPOFFER_eth="eth0"
  # DHCPOFFER_siaddr="192.168.22.254"
  # DHCPOFFER_yiaddr="192.168.22.3"
  # DHCPOFFER_netmask="255.255.255.0"
  # DHCPOFFER_prefix="24"
  rm -f $dhcp_detect_bond_tmp
  if [ -n "$DHCPOFFER_siaddr" ]; then
    echo $msg_delimiter_star_line
    echo "$msg_found_dhcp_service_on_nic: $DHCPOFFER_eth"
    echo "$msg_do_you_want_to_lease_ip_addr_from_existing_dhcp_srv: $DHCPOFFER_siaddr"
    echo "$msg_will_use_available_ip_addr_from_dhcp_srv"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "$msg_note_you_have_to_make_sure_enough_no_of_ip_addr"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "[Y/n] "
    read use_existing_dhcp_srv_ans
    case "$use_existing_dhcp_srv_ans" in
       n|N|[nN][oO]) use_existing_dhcp_srv="no" ;;
       *) use_existing_dhcp_srv="yes" ;;
    esac
  fi
} # end of detect_dhcp_srv_in_lan
#
config_drbl_live_network(){
  local eth_port_no configured_ip_no eth_port configured_port_list configured_ip_no 
  local IP_no dhcp_detect_bond_tmp DHCPOFFER_netmask DHCPOFFER_prefix dhcp_find_rc
  local run_net_cfg try_dhcp_again manually_configure_ans
  # This function only works for Debian based network setting.
  # drbl_live_private_IP_alias_eth_def is global variable from drbl.conf.
  echo "Detecting the network status..."
  eth_port_no="$(LC_ALL=C get-nic-devs | wc -l)"
  configured_ip_no="$(LC_ALL=C get-all-nic-ip -i | wc -w)"
  while [ "$configured_ip_no" -lt "$eth_port_no" ]; do
    [ -n "$(LC_ALL=C route -n | grep -E "^0.0.0.0")" ] && config_gw_opt="--ignore-gw"
    [ -n "$(LC_ALL=C grep -E "^[[:space:]]*nameserver[[:space:]]+\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b" /etc/resolv.conf 2>/dev/null)" ] && config_dns_opt="--ignore-dns"
    # find the configured ports, we will exclude them.
    eth_port="$(LC_ALL=C get-nic-devs)"
    configured_port_list=""
    for i in $eth_port; do
      if [ -n "$(LC_ALL=C drbl-get-ipadd $i)" ]; then
       configured_port_list="$configured_port_list $i"
      fi
    done
    echo "The ethernet port(s) already configured: $configured_port_list"
    if [ -n "$configured_port_list" ]; then
      ocs-live-netcfg --ip-add " " $config_gw_opt $config_dns_opt --ignore-dv "$configured_port_list"
    else
      ocs-live-netcfg --ip-add " " $config_gw_opt $config_dns_opt
    fi
    configured_ip_no="$(get-all-nic-ip -i | wc -w)"
    [ "$configured_ip_no" -eq "$eth_port_no" ] && break
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo $msg_do_not_assign_default_gw_for_DRBL_NIC
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_continue_to_conf_another_NIC"
    echo -n "[Y/n] "
    read continue_conf_eth
    case "$continue_conf_eth" in
       n|N|[nN][oO]) break ;;
    esac
  done

  IP_no="$(get-all-nic-ip -i | wc -w)"
  if [ "$IP_no" -eq 0 ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo $msg_no_ip_address_is_configured
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop"
    exit 1
  fi
  if [ "$IP_no" -eq 1 ]; then
    echo $msg_delimiter_star_line
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Only one network interface was found and configured."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    detect_dhcp_srv_in_lan  # Get use_existing_dhcp_srv and DHCPOFFER_eth
    eth_port="$DHCPOFFER_eth"

    if [ "$use_existing_dhcp_srv" = "yes" ]; then
      # Add a virtual network device on physical net device
      drbl-add-vir-netdev $eth_port drbl0
      echo "Leasing IP address for virtual device drbl0..."
      dhcp_detect_vir_tmp="$(mktemp /tmp/dhcp_detect_vir_tmp.XXXXXX)"
      dhcp_find_rc=1
      while [ "$dhcp_find_rc" -ne 0 ]; do
        drbl-find-dhcp-srv -i drbl0 $dhcp_detect_vir_tmp
        dhcp_find_rc=$?
        if [ "$dhcp_find_rc" -ne 0 ]; then
          echo
          echo "$msg_failed_to_find_any_dhcp_srv: drbl0"
          echo "$msg_do_u_want_to_do_it_again"
	  echo "$msg_say_no_to_manually_config_it"
          echo -n "[Y/n] "
          read try_dhcp_again
          case "$try_dhcp_again" in
            n|N|[nN][oO])
               echo $msg_delimiter_star_line
               echo -n "$msg_do_you_want_to_manually_configure_it? (Y/n) " 
               read manually_configure_ans
               case "$manually_configure_ans" in
                    n|N|[nN][oO])
                       echo "$msg_program_stop"
                       dhcp_find_rc=0
                       # Saving mode, always copy error log to image dir.
                       copy_error_log
                       exit 1
                       ;;
                    *)
                       run_net_cfg="yes"
                       while [ "$run_net_cfg" = "yes" ]; do
                         echo $msg_delimiter_star_line
                         echo "$msg_what_is_the_ip_add_for_virtual_nic_drbl0"
                         read drbl0_ip_prefix
                         echo "$msg_your_input_config_is: $drbl0_ip_prefix"
                         echo -n "$msg_is_that_correct (Y/n) " 
			 read input_check_ans
		         case "$input_check_ans" in
                           n|N|[nN][oO]) run_net_cfg="yes"  ;;
		                      *) run_net_cfg="no" ;;
		         esac
		       done
		       # Write to file     
		       drbl0_ip="$(echo $drbl0_ip_prefix | awk -F"/" '{print $1}')"
		       drbl0_prefix="$(echo $drbl0_ip_prefix | awk -F"/" '{print $2}')"
        	       cat <<-DHCP_END > $dhcp_detect_vir_tmp
DHCPOFFER_eth="drbl0"
DHCPOFFER_siaddr=""
DHCPOFFER_yiaddr="$drbl0_ip"
DHCPOFFER_netmask=""
DHCPOFFER_prefix="$drbl0_prefix"
DHCP_END
                       dhcp_find_rc=0
                       ;;
               esac
               ;;
            *)
               echo "$msg_ok_let_do_it"
               dhcp_find_rc=1
               ;;
          esac
        fi
      done
      # Reset variables before loading them.
      DHCPOFFER_eth=""
      DHCPOFFER_siaddr=""
      DHCPOFFER_yiaddr=""
      DHCPOFFER_netmask=""
      DHCPOFFER_prefix=""
      . $dhcp_detect_vir_tmp
      # Instead of using "dhclient -v drbl0" which will set routing table, we do not want. Here we use static address without routing table.
      if [ -n "$DHCPOFFER_yiaddr" ]; then
        if [ -z "$DHCPOFFER_prefix" ]; then
          # Since check_dhcp does not provide netmask/inet prefix length info, borrow it from bond card's info
	  # ip command only accepts prefix length, not netmask. E.g.
	  # 2: eth0    inet 192.168.76.254/24 brd 192.168.76.255 scope global eth0...
	  DHCPOFFER_prefix="$(LC_ALL=C ip -o -f inet addr show $eth_port | awk -F" " '{print $4}' | awk -F"/" '{print $2}')"
        fi
        ip addr add $DHCPOFFER_yiaddr/$DHCPOFFER_prefix dev drbl0
      else
        [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
        echo "Failed to lease DHCP IP address for network interface drbl0!"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        echo "$msg_program_stop!"
        my_ocs_exit 1
      fi
      # Write result for later use in drblpush.
      if grep -Eq "^use_existing_dhcp_srv=.*" /etc/drbl/drbl.conf; then
        perl -pi -e "s/^use_existing_dhcp_srv=.*/use_existing_dhcp_srv=yes # Modified by drbl-live/g" /etc/drbl/drbl.conf
      else
        echo "use_existing_dhcp_srv=yes # Modified by drbl-live" >> /etc/drbl/drbl.conf
      fi
      rm -f $dhcp_detect_vir_tmp
    elif [ "$use_existing_dhcp_srv" = "no" ]; then
      # Write result for later use in drblpush.
      if grep -Eq "^use_existing_dhcp_srv=.*" /etc/drbl/drbl.conf; then
        perl -pi -e "s/^use_existing_dhcp_srv=.*/use_existing_dhcp_srv=no # Modified by drbl-live/g" /etc/drbl/drbl.conf
      else
        echo "use_existing_dhcp_srv=no # Modified by drbl-live" >> /etc/drbl/drbl.conf
      fi
      if [ -z "$limit_pxe_drbl_client" ]; then
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
        echo "$msg_one_NIC_one_IP_limitation_prompt"
        echo "$msg_if_lease_IP_add_to_pxe_etherboot_only"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        echo -n "[Y/n] "
        read limit_pxe_drbl_client_ans
        case "$limit_pxe_drbl_client_ans" in
           n|N|[nN][oO]) limit_pxe_drbl_client="no" ;;
           *) limit_pxe_drbl_client="yes" ;;
        esac
      else
        case "$limit_pxe_drbl_client" in
           n|N|[nN][oO]|y|Y|[yY][eE][sS]) true ;;
           *) 
              [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
              echo "\"$limit_pxe_drbl_client\" is an unknown or unsupported option for limit_pxe_drbl_client."
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
              echo "$msg_program_stop"
              exit 1
              ;;
        esac
      fi
      echo -n "$msg_only_one_IP_so_create_alias_IP "
      alias_done="no"
      # Get the NIC device name for the only one device
      nic_dev_only="$(get-nic-devs | head -n 1)"
      i="$drbl_live_private_IP_alias_eth_def"
      while [ "$alias_done" = "no" ]; do
        if ! ping -c 3 192.168.$i.254 &>/dev/null; then
          ifconfig ${nic_dev_only}:1 192.168.$i.254 netmask 255.255.255.0
          alias_done="yes"
        else
          i=$((i+1))
        fi
      done
      if ! grep -E -e "^auto[[:space:]]+${nic_dev_only}:1" /etc/network/interfaces; then
        cat <<-NET_END >> /etc/network/interfaces
auto ${nic_dev_only}:1
iface ${nic_dev_only}:1 inet static
	address 192.168.$i.254
	netmask 255.255.255.0
NET_END
      fi
    fi

    echo "$msg_done!"
  else
    # More than one IP address, so it's not necessary to use alias IP address.
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo $msg_more_than_1_IP_some_for_DRBL_clients
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi

  if [ -z "$(LC_ALL=C route -n | grep -E "^0.0.0.0")" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "No default gateway was configured! Did you enter it or the input gateway is the correct one ?"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "The routing table:"
    echo "---------------------------------------------------------"
    LC_ALL=C route -n
    echo "---------------------------------------------------------"
    echo "$msg_program_stop"
    exit 1
  fi
} # end of config_drbl_live_network
#
get_existing_language(){
   # show existing language file
   local ANS_TMP=$1
   local rec_lang=
   local lang_shown
   local TMP=`mktemp /tmp/ocs.XXXXXX`
   trap "[ -f "$TMP" ] && rm -f $TMP" HUP INT QUIT TERM EXIT
   numfiles=`LC_ALL=C ls $DRBL_SCRIPT_PATH/lang/bash/*.UTF-8 2> /dev/null | wc -l`
   numfiles=`LC_ALL=C expr $numfiles + 0`
   # list the previous saved images
   # the list of images can be put in one page
   filelist=""
   numfiles=0
   for file in $DRBL_SCRIPT_PATH/lang/bash/*.UTF-8; do
     fileinfo="$(basename $file)"
     fileinfo_="$(echo $fileinfo | sed -e "s/\.UTF-8//g")"
     # Convert to human can read, i.e. show "English" instead of "en_US"
     eval lang_shown=\$msg_locale_${fileinfo_}
     # Replace the space with "-" so that dialog won't fail.
     lang_shown="$(LC_ALL=C echo $lang_shown | sed -r -e "s/[[:space:]]/_/g")"
     if [ -n "$lang_shown" ]; then
       filelist="$filelist $fileinfo $lang_shown"
     else
       filelist="$filelist $fileinfo $fileinfo_"
     fi
     numfiles=`LC_ALL=C expr $numfiles + 1`
   done
   # Find the system lang setting "ocs_lang"
   [ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf
   if [ -n "$ocs_lang" ]; then
     preferred_lang_opt="--default-item $ocs_lang"
   fi

   if [ "$numfiles" -gt 0 ]; then
     if [ "$numfiles" -lt "$MAX_DIALOG_HEIGHT" ]; then
       height="$numfiles"
     else
       height="$MAX_DIALOG_HEIGHT"
     fi
     $DIA \
       --backtitle "$msg_nchc_free_software_labs" \
       --title "$msg_nchc_clonezilla | $msg_mode: $ocs_mode_prompt" \
       $preferred_lang_opt \
       --menu "$msg_choose_the_language_in_recovery_iso_zip:" 0 0 \
       $height $filelist 2> $TMP
     rec_lang="$(cat $TMP)"
   else
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "No lanaguage file was found! $msg_program_stop!!!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     exit 1
   fi
   [ -f "$TMP" ] && rm -f $TMP
   # return the valule
   echo $rec_lang > $ANS_TMP
} # end of get_existing_language
#
gen_locale_if_not_found() {
  local lang_region_tmp="$1"
  local lang_tmp="$2"
  # Generate locale files.
  # The outputs for localedef --list-archive are like:
  # en_US.utf8
  # zh_TW.utf8
  # While we use en_US.UTF-8 or zh_TW.UTF-8 as the locale.
  # If it's not a archive, the locales will be saved as the name of a subdirectory in /usr/lib/locale where per-category compiled files are placed.
  [ -z "$lang_region_tmp" ] && echo "You should assign lang_region_tmp in function gen_locale_if_not_found!!!" && exit 1
  [ -z "$lang_tmp" ] && echo "You should assign lang_tmp in function gen_locale_if_not_found!!!" && exit 1
  if [ -z "$(localedef --list-archive | sed -e 's|\.utf8|.UTF-8|g' | grep -iw "$lang_tmp")" ] && \
     [ -z "$(unalias ls 2>/dev/null; ls /usr/lib/locale 2>/dev/null | sed -e 's|\.utf8|.UTF-8|g' | grep -iw "$lang_tmp")" ]
  then 
    echo -n "Generating locale $lang_tmp by: localedef -f UTF-8 -i $lang_region_tmp $lang_tmp... "
    localedef -f UTF-8 -i $lang_region_tmp $lang_tmp
    echo "done!"
  fi
} # end of gen_locale_if_not_found
#
parse_cmdline_option() {
  # The reason we have this function is some boot parameter is like xxx="-k -x", therefore we can not just use 
  # case $param in
  # xxx=*) ...
  # method, since it won't catch the right xxx. It will just catch xxx="-k.
  # //NOTE// This function won't work for those boot parameter can not be a varialble, e.g. live-boot-media (with -, it's not a legal variable), since if we assign it by ". live-boot-media=/live-hd", it will failed.
  local param_ parse_tmp cmdl_file
  #
  while [ $# -gt 0 ]; do
    case "$1" in
      -c|--cmdline-file)
         shift
         if [ -z "$(echo $1 |grep ^-.)" ]; then
           # skip the -xx option, in case 
           cmdl_file="$1"
           shift
         fi
         [ -z "$cmdl_file" ] && echo "-c is used, but no cmdl_file assigned." && exit 1
         ;;
      -*) echo "${0}: ${1}: invalid option" >&2
          exit 2 ;;
      *)  break ;;
    esac
  done
  param_="$1"
  parse_tmp="$(mktemp /tmp/cmdtmp.XXXXXX)"

  [ -z "$cmdl_file" ] && cmdl_file="/proc/cmdline"
  if [ ! -e "$cmdl_file" ]; then
    echo "cmdl_file ($cmdl_file) does _NOT_ exist!"
    exit 1
  fi

  for ik in $param_; do
    # The parameter maybe like: xxx=xyz, xxx="xyz", xxx="-k -x", or "xxx=-k -x" (see below)
    ###
    # The cases like xxx="-k -x" or "xxx=a b c", which allows spaces between " "
    # Possible complicated commands:
    # ocs_prerun="sshfs -o nonempty -p 22 root@myhost.mymachine:/home/partimag/ /home/partimag"
    # ocs_prerun="mount -t cifs -o username=user,password=pass //127.0.0.1/test /home/partimag"
    # ocs_prerun="sudo mount -t cifs -o user=ghost,password=ghost123 //192.168.1.1/tftpboot$/images/clonezilla /home/partimag" # Ref: https://sourceforge.net/projects/clonezilla/forums/forum/663168/topic/4589215, for samba share with hidden share, a "$" is in the end of dir name.
    # Therefore we have to add "/" ":" "=" "," "@", "\\$"
    #
    # For gurb2 1.99, although \" is put in boot parameter,
    # it will be shown in /proc/cmdline as the following:
    # Boot parameters assigned   ->  /proc/cmdline
    # 4 cases:                   
    # (1) ocs_prerun="sleep 5"   ->  "ocs_prerun=sleep 5" (Yes, with " in the beginning and in the end.
    # (2) ocs_prerun='sleep 5'   ->  "ocs_prerun=sleep 5"
    # (3) ocs_prerun=\"sleep 5\" ->   ocs_prerun=\"sleep 5\"
    # (4) ocs_prerun=dhclient    ->   ocs_prerun=dhclient
    # So far for syslinux (4.04), no such problem. Just use ocs_prerun="sleep 5".
    # Some examples about parsing these parameters:
    # =================
    # ocs_prerun1="ps -efw |grep 'bound 169.254.9.223' &"
    # ocs_prerun2="ps -efw |grep '[a-z]'"
    # ocs_prerun3="sshfs -o nonempty -p 22 root@myhost.mymachine:/home/partimag/ /home/partimag"
    # ocs_prerun4="mount -t cifs -o username=user,password=pass //127.0.0.1/test /home/partimag"
    # ocs_prerun5="sudo mount -t cifs -o user=ghost,password=ghost123 //192.168.1.1/tftpboot$/images/clonezilla /home/partimag" 
    # "ocs_prerun6=sleep 5"
    # "ocs_prerun7=sleep 5"
    # ocs_prerun8=\"sleep 5\"
    # ocs_prerun9="sed -i -e '/[1-6]:23:/ d' -e '/1:2345:respawn/ d'"
    # ocs_prerun10="sed -i -e s@#T0@T0@g -e s@dev/tty@dev/ttyS0@g /etc/inittab"
    # ocs_prerun11="lsblk|grep ' 1 '|grep ..sd|sort -k4hr|sed 's|..\(sd..\).*|mount /dev/\1 /mnt|;1p;d'|bash"
    # ocs_prerun12="ps -efw |grep \"[a-z]\""
    # ocs_repository=smb://name:passwd@192.168.1.1/images/
    # =================
    # ///NOTE/// We can not make it in _one_ case like this:
    # LC_ALL=C grep -oE -- "(\"|)*$ik=(\\\\\"|\")*([[:space:]]|[[:alnum:]]|_|-|\.|\/|:|=|,|@|\\$|>|\^|\*)*(\\\\\"|\")*([[:space:]]|$)+" $cmdl_file | sed -r -e "s|=\\\\\"|=\"|g" -e "s@\\\\\"([[:space:]]|$)+@\"@g" | sed -r -e 's|^\"(.*)=|\1=\"|g' > $parse_tmp
    # Since it might get wrong parsing like this:
    # root@debian:~# cat /proc/cmdline 
    # initrd=/live/initrd.img boot=live config  noswap nolocales edd=on nomodeset ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_keymap="" ocs_live_batch="no" ocs_lang="" vga=788 ip= nosplash BOOT_IMAGE=/live/vmlinuz 
    # root@debian:~# grep -oE -- '("|)*ocs_lang=(\\"|")*([[:space:]]|[[:alnum:]]|_|-|\.|\/|:|=|,|@|\$|>|\^|\*)*(\\"|")*([[:space:]]|$)+' /proc/cmdline
    # ocs_lang="" vga=788 ip= nosplash BOOT_IMAGE=/live/vmlinuz <- WRONG RESULT. We just want ocs_lang=""
    if LC_ALL=C grep -Eq "($ik=\"|$ik=\\\\\")" $cmdl_file; then
      # For case like: ocs_prerun="sleep 5" or ocs_prerun=\"sleep 5\"
      LC_ALL=C grep -oE -- "$ik=(\"|\\\\\")[^\"]*(\"|\\\\\")([[:space:]]|$)+" $cmdl_file | sed -r -e "s|=\\\\\"|=\"|g" -e "s@\\\\\"([[:space:]]|$)+@\"@g" | sed -r -e 's|^\"(.*)=|\1=\"|g' > $parse_tmp
    elif LC_ALL=C grep -Eq "\"$ik=" $cmdl_file; then
      # For case like: "ocs_prerun=sleep 5", "ocs_prerun1=mount UUID=XXXYYZZ /mnt"
      # 2012/08/20 Without separating "=", it might fail in this case:
      # "ocs_prerun1=mount UUID=XXXYYZZ /mnt" -> ocs_prerun1=mount UUID="XXXYYZZ /mnt"
      # Therefore we have to use: sed -r -e 's|^\"(.*=)(.*=.*)*|\1\"\2|g'
      # 2020/12/26 When two "=" in the variable, e.g.,:
      # "ocs_live_run=ocs-sr -q2 -j2 -z1p -p poweroff savedisk autoname-wpfx=fox serialno=xyz"
      # it fails at:
      # ocs_live_run=ocs-sr -q2 -j2 -z1p -p poweroff savedisk autoname-wpfx="fox serialno=xyz"
      # since sed is greedy regex.
      # Therefore we have to use non-greedy regex language, perl, for this purpose: 
      # perl -pi -e 's/(^")(.*?=)(.*=.*)*/$2"$3/g' $parse_tmp
      # Ref: http://stackoverflow.com/questions/9681393/sed-multiple-patterns-on-the-same-line-how-to-match-parse-first-one
      #      https://www.ultraedit.com/support/tutorials-power-tips/ultraedit/non-greedy-perl-regex.html
      LC_ALL=C grep -oE -- "\"$ik=[^\"]*\"([[:space:]]|$)+" $cmdl_file | \
	       sed -r -e "s|=\\\\\"|=\"|g" -e "s@\\\\\"([[:space:]]|$)+@\"@g" \
	       > $parse_tmp
      perl -pi -e 's/(^")(.*?=)(.*=.*)*/$2"$3/g' $parse_tmp
    else
      # This is for case xxx=xyz, no space in its assignment
      LC_ALL=C grep -oE -- "$ik=[^[:space:]]*([[:space:]]|$)+" $cmdl_file > $parse_tmp
    fi
    # now we can get the variables
    # . $parse_tmp <--- One more thing to do.
    # In we just read the variable using ". $parse_tmp", and it happends to have "$" in the variable, then the way will go wrong. E.g. the output file "/tmp/cmdtmp.XXXXXX" contains this line:
    # ocs_prerun="mount -t cifs -o user=steven,domain=ABC.COM,password=12$ABC34 //serv/images /home/partimag"
    # By running ". /tmp/cmdtmp.XXXXXX", the ocs_prerun will be:
    # mount -t cifs -o user=steven,domain=ABC.COM,password=12 //serv/images /home/partimag
    # It's because $ABC34 is nothing here. Therefore we have to protect "$" in the temp file.
    perl -pi -e 's|\$|\\\$|g' $parse_tmp
    . $parse_tmp
  done
  [ -f "$parse_tmp" ] && rm -f $parse_tmp
} # parse_cmdline_option
#
output_netinstall_boot_menu() {
  local TDIR  # Where netinstall kernel/initrd exists (e.g. /tftpboot/nbi_img)
  local NB_CFG_DIR_FNAME  # Where pxeliux cfg file exists (e.g. /tftpboot/nbi_img/pxelinux.cfg/)
  local menu_hint ni_ver ni_arch boot_file_dir
  local nb_mode_="pxe" # Default mode if not assigned
  local usb_boot_media_="no"  # Default not to prepend the setting for USB boot media
  # output the netinstall menu
  # Here 2 types: Linux and BSD
  # The netinstall kernel files (linux) or pxeboot file (bsd) in /tftpboot/nbi_img are, e.g.:
  # Type 1: for Linux, the file names are like:
  # vmlinuz-netinstall-CentOS-4.6-i386
  # vmlinuz-netinstall-CentOS-4.6-x86_64
  # vmlinuz-netinstall-CentOS-5.1-i386
  # vmlinuz-netinstall-CentOS-5.1-x86_64
  # vmlinuz-netinstall-Debian-etch-amd64
  # vmlinuz-netinstall-Debian-etch-i386
  # vmlinuz-netinstall-Debian-sarge-i386
  # vmlinuz-netinstall-Fedora-7-i386
  # vmlinuz-netinstall-Fedora-7-x86_64
  
  # Type 2: for BSD, the file names are like:
  # OpenBSD-4.2-i386-pxeboot.0
  # FreeBSD-7.0-i386-pxeboot.0

  while [ $# -gt 0 ]; do
   case "$1" in
     -e|--efi) nb_mode_="efi"; shift;;
     -p|--prefix)
           shift
           if [ -z "$(echo $1 |grep ^-.)" ]; then
             # skip the -xx option, in case 
             boot_file_dir="$1"
             shift
           fi
           if [ -z "$boot_file_dir" ]; then
             echo "-p is used, but no \"boot_file_dir\" assigned."
             echo "$msg_program_stop"
             [ "$save_restore_error_log" = "yes" ] && copy_error_log
             exit 1
           fi
           ;;
     -u|--usb-boot-media) usb_boot_media_="yes"; shift;;
     -*)   echo "${0}: ${1}: invalid option" >&2
           exit 2 ;;
     *)    break ;;
   esac
  done

  TDIR="$1" 
  NB_CFG_DIR_FNAME="$2"

  if [ "$nb_mode_" = "efi" -a "$usb_boot_media_" = "yes" ]; then
     # This is for drbl-usb-netinstall use. For the netboot of DRBL clients,
     # the gen-grub-efi-nb-menu will prepend those configs for diskless clients.
     cat <<-PXE_END > $NB_CFG_DIR_FNAME
# Netboot menu for grub
set pref=/boot/grub
set default="0"
insmod efi_gop
insmod efi_uga
if [ x\$feature_default_font_path = xy ] ; then
   font=unicode
else
   font=\$prefix/unifont.pf2
fi

if loadfont \$font; then
  set gfxmode=auto
  insmod gfxterm
  terminal_output gfxterm
fi
set timeout=30
set hidden_timeout_quiet=false
insmod png
if background_image \$pref/drblwp.png; then
  set color_normal=black/white
  set color_highlight=green/white
else
  set color_normal=white/black
  set color_highlight=black/white
fi

# Decide if the commands: linux/initrd (default) or linuxefi/initrdefi
set linux_cmd=linux
set initrd_cmd=initrd
export linux_cmd initrd_cmd
# Since "linux/initrd" works for uEFI boot, no matter it's secure boot or not. Just use them.
# if [ "\${grub_cpu}" = "x86_64" -o "\${grub_cpu}" = "i386" ];then
#   set linux_cmd=linuxefi
#   set initrd_cmd=initrdefi
# fi

PXE_END
  fi
  
  # Type 1: Linux
  for inet in $TDIR/vmlinuz-netinstall-*; do
   # /tftpboot/nbi_img/vmlinuz-netinstall-CentOS-4-i386
   # /tftpboot/nbi_img/initrd-netinstall-CentOS-4-i386.img

   [ ! -e "$inet" ] && continue
   # Truncate "vmlinuz-"
   # For debina based, back convert x86-64 to x86_64, since alien convert x86_64 to x86-64.
   kernel="$(basename $inet)"
   inet_="$(basename $inet | sed -e "s/^vmlinuz-//g" -e "s/x86-64/x86_64/g")"
   img_menu="$(echo "$inet_" | awk -F"-" '{print $1"-"$2"-"$3"-"$4}')"
   img="$(unalias ls 2>/dev/null; ls $TDIR/*${inet_}* 2>/dev/null)"
   img="$(basename $img)"

   extra_append=""
   if [ -n "$(echo $inet | grep -i "\-debian-woody" 2>/dev/null)" ]; then
      # For Debian Woody, we use extra options bf24
      # refer to http://www.debianplanet.com/node.php?id=818&cid=13384
      NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      extra_append="flavor=bf2.4"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -i "\-debian-sarge" 2>/dev/null)" ]; then
      # For Debian Sarge, we need extra options in append
      # refer to http://opensource.nchc.org.tw/debian/dists/sarge/main/installer-i386/current/images/netboot/pxelinux.cfg/default
      NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      extra_append="root=/dev/rd/0 devfs=mount,dall rw  --"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-debian-etch" 2>/dev/null)" ]; then
      # Ref: http://free.nchc.org.tw/debian/dists/etch/main/installer-i386/current/images/netboot//debian-installer/i386/pxelinux.cfg/default
      NETINSTALL_RAMDISK_SIZE=""
      extra_append="vga=normal"
   elif [ -n "$(echo $inet | grep -iE "\-debian-" 2>/dev/null)" ]; then
      # For version >= lenny, gtk netinstall mode is available, actually we can turn on it by adding "video=vesa:ywrap,mtrr vga=788" in the boot parameters. However, since normally those people use debian can accept text mode, we do not put "video=vesa:ywrap,mtrr vga=788" here.
      # http://free.nchc.org.tw/debian/dists/lenny/main/installer-i386/current/images/netboot/gtk/debian-installer/i386/boot-screens/txt.cfg
      NETINSTALL_RAMDISK_SIZE=""
      extra_append="vga=normal"
      menu_hint="# Hint: To turn on gtk mode installation, append 'video=vesa:ywrap,mtrr vga=788' in the boot parameters"
   elif [ -n "$(echo $inet | grep -iE "\-redhat-" 2>/dev/null)" ]; then
      # For RedHat, enable reiserfs when installing
      NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      extra_append="reiserfs"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-fedora-" 2>/dev/null)" ]; then
      # Fedora vmlinuz name e.g. vmlinuz-netinstall-Fedora-17-x86_64
      ni_ver="$(echo $inet | cut -f 4 -d "-")"
      ni_arch="$(echo $inet | cut -f 5 -d "-")"
      # ramdisk_size only necessary for fedora 1-4, from fc5, it's initramfs, ramdisk_size is not used anymore 
      if [ -n "$(echo $inet | grep -iE "\-fedora-[1-4]-" 2>/dev/null)" ]; then
        NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      else
        NETINSTALL_RAMDISK_SIZE=""
      fi
      if [ -n "$(echo $inet | grep -iE "\-fedora-([5-9]|1[1-6])-" 2>/dev/null)" ]; then
        # For Fedora 5 to 16.
        extra_append=""
      elif [ -n "$(echo $inet | grep -iE "\-fedora-(1[7-9]|20)-" 2>/dev/null)" ]; then
        # For Fedora 16 to 20.
        echo "Using Fedora installation repository \"$fedora_url_site\" from drbl.conf"
        extra_append="inst.repo=$fedora_url_site/fedora/linux/releases/$ni_ver/Fedora/$ni_arch/os"
      else
        # For Fedora 21 or later
        echo "Using Fedora installation repository \"$fedora_url_site\" from drbl.conf"
        extra_append="inst.repo=$fedora_url_site/fedora/linux/releases/$ni_ver/Server/$ni_arch/os"
      fi
      # For Fedora, enable reiserfs when installing
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-centos-" 2>/dev/null)" ]; then
      # CentOS vmlinuz name e.g. vmlinuz-netinstall-CentOS-7-x86_64
      ni_ver="$(echo $inet | cut -f 4 -d "-")"
      ni_arch="$(echo $inet | cut -f 5 -d "-")"
      # ramdisk_size only necessary for centos 1-4, from 5, it's initramfs, ramdisk_size is not used anymore 
      if [ -n "$(echo $inet | grep -iE "\-centos-[1-4]-" 2>/dev/null)" ]; then
        NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      else
        NETINSTALL_RAMDISK_SIZE=""
      fi
      if [ -n "$(echo $inet | grep -iE "\-centos-[5-6]-" 2>/dev/null)" ]; then
        # For CentOS 5 to 6.
        extra_append=""
      elif [ -n "$(echo $inet | grep -iE "\-centos-7-" 2>/dev/null)" ]; then
        # CentOS 7
        # Ref: https://bugzilla.redhat.com/show_bug.cgi?id=810005
        echo "Using CentOS installation repository \"$centos_url_site\" from drbl.conf"
	# http://free.nchc.org.tw/centos/7/os/x86_64/
        extra_append="inst.repo=$centos_url_site/centos/$ni_ver/os/$ni_arch"
      else
        # CentOS 8 or later
        echo "Using CentOS installation repository \"$centos_url_site\" from drbl.conf"
	# http://free.nchc.org.tw/centos/8/BaseOS/x86_64/
        extra_append="inst.repo=$centos_url_site/centos/$ni_ver/BaseOS/$ni_arch/os/"
      fi
      # For CentOS, enable reiserfs when installing
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "(\-mandrake-|\-mandriva-)" 2>/dev/null)" ]; then
      # For Mandrake/Mandriva
      # use larger ramdisk size for Mandrake, overwrite the default one.
      NETINSTALL_RAMDISK_SIZE=128000
      extra_append="acpi=ht vga=788 splash=silent label vgalo"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-ubuntu-[a-e]" 2>/dev/null)" ]; then
      # For other Ubuntu: 5.10, 6.06, 6.10
      # ref to ftp://linux.nchc.org.tw/distributions/ubuntu/dists/hoary/main/installer-i386/current/images/netboot/ubuntu-installer/i386/pxelinux.cfg/default
      NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      extra_append="root=/dev/rd/0 rw  --"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-ubuntu-[f-i]" 2>/dev/null)" ]; then
      # For Ubuntu Feisty (7.04)
      # ref to http://opensource.nchc.org.tw/ubuntu/dists/feisty/main/installer-i386/current/images/netboot/ubuntu-installer/i386/pxelinux.cfg/default
      # It's initramfs, so ramdisk_size is no more.
      NETINSTALL_RAMDISK_SIZE=""
      extra_append="vga=normal --"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -iE "\-ubuntu-[j-z]" 2>/dev/null)" ]; then
      # Ref: http://free.nchc.org.tw/ubuntu/dists/jaunty/main/installer-i386/current/images/netboot/gtk/ubuntu-installer/i386/boot-screens/text.cfg
      # It's initramfs, so ramdisk_size is no more.
      NETINSTALL_RAMDISK_SIZE=""
      # Looks like gtk netinstall in not quite stable for jaunty, here we turn off framebuffer mode.
      #extra_append="video=vesa:ywrap,mtrr vga=788 --"
      extra_append="vga=normal --"
      menu_hint="# Hint: To turn on gtk mode installation, append 'video=vesa:ywrap,mtrr vga=788' in the boot parameters"
   elif [ -n "$(echo $inet | grep -i "\-suse-" 2>/dev/null)" ]; then
      # For SuSE
      # For extra_append, refer to something like 
      # http://free.nchc.org.tw/SuSE/SuSE/i386/9.3/boot/loader/isolinux.cfg
      # use larger ramdisk size, overwrite the default one.
      NETINSTALL_RAMDISK_SIZE=128000
      extra_append="splash=silent showopts"
      menu_hint=""
   elif [ -n "$(echo $inet | grep -i "\-opensuse-" 2>/dev/null)" ]; then
      # For OpenSuSE
      # For extra_append, refer to something like 
      # http://ftp.cs.pu.edu.tw/Linux/OpenSuse/distribution/SL-10.0-OSS/inst-source/boot/loader/isolinux.cfg
      # use larger ramdisk size, overwrite the default one.
      NETINSTALL_RAMDISK_SIZE=128000
      extra_append="splash=silent showopts"
      menu_hint=""
   else
      NETINSTALL_RAMDISK_SIZE="$NETINSTALL_RAMDISK_SIZE_DEF"
      extra_append=""
      menu_hint=""
   fi

   # skip if we can not find the menu, img or kernel.
   [ -z "$img_menu" ] && continue
   [ -z "$img" -o -z "$kernel" ] && continue

   # Generate the description:
   # EX for i: rh-8.0-netinstall
   # create the description for the netinstall image
   des="$(echo $img_menu | sed -e "s/^netinstall-//g" | sed -e "s/-/ /g")"
   des="${des} installation via network"
   # For initramfs, ramdisk_size is no more.
   if [ -n "$NETINSTALL_RAMDISK_SIZE" ]; then
     ramdisk_size_opt="ramdisk_size=$NETINSTALL_RAMDISK_SIZE"
   else
     ramdisk_size_opt=""
   fi

   if [ "$nb_mode_" = "pxe" ]; then
     echo "Adding $img_menu menu..."
     [ -n "$verbose" ] && echo "extra option in append: $extra_append"    
     cat <<-PXE_END >> $NB_CFG_DIR_FNAME
label $img_menu
  # MENU DEFAULT
  MENU HIDE
  MENU LABEL $des
  # MENU PASSWD
  kernel $boot_file_dir$kernel
  append initrd=$boot_file_dir$img $ramdisk_size_opt $extra_append
  $menu_hint
  TEXT HELP
  * Boot menu for BIOS machine
  * $des
  ENDTEXT

PXE_END
   else
    # Only output x86-64/amd64 one for uEFI mode
    if [ -n "$(echo $kernel | grep -iE -- "(x86-64|x86_64|amd64|i386)")" ]; then
     echo "Adding $img_menu menu..."
     [ -n "$verbose" ] && echo "extra option in append: $extra_append"    
     cat <<-PXE_END >> $NB_CFG_DIR_FNAME
menuentry "$des" --id $img_menu {
  set check_signatures=no
  echo "Enter netinstall for $img_menu..."
  echo "Loading Linux kernel..."
  \$linux_cmd $boot_file_dir$kernel $ramdisk_size_opt $extra_append
  echo "Loading initial ramdisk..."
  \$initrd_cmd $boot_file_dir$img
}

PXE_END
    fi
   fi
  done

  # Type 2: BSD
  for inet in $TDIR/*-pxeboot.0; do
   # Ex: /tftpboot/nbi_img/FreeBSD-7.0-i386-pxeboot.0
   [ ! -e "$inet" ] && continue
   # Truncate "-pxeboot.0"
   inet_="$(basename $inet | sed -e "s/-pxeboot.0//g")"
   img_menu="$(echo "$inet_" | awk -F"-" '{print $1"-"$2"-"$3}')-netinstall"
   img="$(unalias ls 2>/dev/null; ls $TDIR/*${inet_}* 2>/dev/null)"
   img="$(basename $img)"
   # create the description for the netinstall image
   des="$(echo $img_menu | sed -e "s/-netinstall$//g" | sed -e "s/-/ /g")"
   des="${des} installation via network"
   [ -z "$img_menu" ] && continue
   echo "Adding $img_menu menu..."
   if [ "$nb_mode_" = "pxe" ]; then
     cat <<-PXE_END >> $NB_CFG_DIR_FNAME
label $img_menu
  # MENU DEFAULT
  MENU HIDE
  MENU LABEL $des
  # MENU PASSWD
  kernel $boot_file_dir$img
  TEXT HELP
  * Boot menu for BIOS machine
  * $des
  ENDTEXT

PXE_END
   else
     cat <<-PXE_END >> $NB_CFG_DIR_FNAME
menuentry "$des" --id $img_menu {
  echo "Enter netinstall for $img_menu..."
  echo "Loading Linux kernel..."
  \$linux_cmd $boot_file_dir$img
}

PXE_END
   fi
  done
} # end of output_netinstall_boot_menu
#
get_syslinux_binary_for_dos_linux() {
  local sysl_dir="$1"
  # syslinux_ver is not required. If it's not assigned, the latest one on the web will be used.
  local syslinux_ver="$2"
  local syslinux_tarball syslinux_ver_subdir syslinux_extra_c32 dirprefix syslinux_efi_coms
  local found_url valid_ulr
  [ -z "$sysl_dir" -o ! -d "$sysl_dir" ] && echo "No sysl_dir!" && exit 1
  # syslinux_binsrc_url is like:
  # http://www.kernel.org/pub/linux/utils/boot/syslinux/
  # For any version 4.xx, it will be found in http://www.kernel.org/pub/linux/utils/boot/syslinux/4.xx/. However, the latest one is in http://www.kernel.org/pub/linux/utils/boot/syslinux/
  if [ -z "$syslinux_ver" ]; then
    # If no version is assigned, find the latest one.
    syslinux_tarball="$(LC_ALL=C list_latest_tarball -f xz $syslinux_binsrc_url)" 
    syslinux_ver="$(LC_ALL=C echo "$syslinux_tarball" | sed -e "s/^syslinux-//g" -e "s/.tar.xz//g")"
  else
    syslinux_tarball="syslinux-${syslinux_ver}.tar.xz"
  fi
  if [ -z "$(echo $syslinux_ver | grep -iE -- "-pre[[:digit:]]+")" ]; then
    # Stable release, not testing version.
    # Convert the version number to subdir name, e..g 4.04 -> 4.xx
    syslinux_ver_subdir="$(LC_ALL=C echo "$syslinux_ver" | sed -r -e "s/\.[[:digit:]]*$/\.xx/g")"
  else
    # Testing release. File name is like: syslinux-6.02-pre16.tar.xz
    # The URL for such a testing version is like: http://free.nchc.org.tw/syslinux/Testing/6.02/
    syslinux_ver_subdir="$(LC_ALL=C echo "$syslinux_ver" | sed -r -e "s/-pre[[:digit:]]+$//g")"
    syslinux_ver_subdir="Testing/$syslinux_ver_subdir"
  fi
  found_url="false"
  while [ "$found_url" = "false" ]; do
    if `check_url $syslinux_binsrc_url/$syslinux_ver_subdir/$syslinux_tarball`; then
      valid_ulr="$syslinux_binsrc_url/$syslinux_ver_subdir/$syslinux_tarball"
      found_url="true"
    else
      # E.g., 6.04 -> 6.03
      # Because Debian has syslinux like: 3:6.04~git20190206.bf6db5b4+dfsg1-1, but
      # actually 6.04 is not officially released on syslinux.org (Sep/25/2021).
      syslinux_ver="$(LC_ALL=C echo "scale=2; $syslinux_ver - 0.01" | bc -l)"
      echo "Try earlier syslinux version $syslinux_ver..."
      syslinux_tarball="syslinux-${syslinux_ver}.tar.xz"
    fi
  done
  echo "Downloading $valid_ulr..."
  wget $wget_opt -P $sysl_dir $valid_ulr
  # For syslinux 6.x, due to EFI feature was added, *.c32 might be in different dirs, e.g. for menu.c32:
  # $ tar tvJf syslinux-5.10.tar.xz | grep -w menu.c32
  # -rwxrwxr-x mfleming/syslinux  25808 2013-06-05 03:33 syslinux-5.10/com32/menu/menu.c32
  # $ tar tvJf syslinux-6.01.tar.xz |grep -w menu.c32
  # -rwxrwxr-x mfleming/syslinux  25708 2013-07-04 21:26 syslinux-6.01/bios/com32/menu/menu.c32
  # -rwxrwxr-x mfleming/syslinux  26012 2013-07-04 21:27 syslinux-6.01/efi32/com32/menu/menu.c32
  # -rwxrwxr-x mfleming/syslinux  31416 2013-07-04 21:28 syslinux-6.01/efi64/com32/menu/menu.c32
  # Therefore we have to parse them...
  # //NOTE// The syslinux tarball (<= ver 6.03) from syslinux.org only contains x86 (32-bit) programs for GNU/Linux, no x86-64 ones.
  if [ -n "$(tar -tvJf $sysl_dir/syslinux-${syslinux_ver}.tar.xz | \
	     grep -w "bios/com32/menu/menu.c32")" ]; then
    dirprefix="bios/"
  else
    dirprefix_bios=""
  fi 
  # For syslinux 5.x, ./com32/elflink/ldlinux/ldlinux.c32, ./com32/lib/libcom32.c32, and ./com32/libutil/libutil.c32 are required.
  for i in $sys_pxelinux_v5p_required_c32; do
    if [ -n "$(LC_ALL=C tar -tvJf $sysl_dir/syslinux-${syslinux_ver}.tar.xz | grep -Ew $i)" ]; then
      syslinux_extra_c32="syslinux-${syslinux_ver}/${dirprefix}com32/elflink/ldlinux/ldlinux.c32 syslinux-${syslinux_ver}/${dirprefix}com32/lib/libcom32.c32 syslinux-${syslinux_ver}/${dirprefix}com32/libutil/libutil.c32" 
      break
    fi
  done
  # Extract win32/syslinux.exe, linux/syslinux and more. This is for BIOS machine
  echo "Extracting files..."
  mkdir -p $sysl_dir/bios/
  (
   cd $sysl_dir/bios/
   # From syslinux 3.73, linux/syslinux is hardlink to linux/syslinux-nomtools, therefore we have to use --wildcards to extract it. Otherwise it will fail.
   tar --wildcards -xvJf ../syslinux-${syslinux_ver}.tar.xz syslinux-${syslinux_ver}/${dirprefix}com32/menu/menu.c32 syslinux-${syslinux_ver}/${dirprefix}com32/menu/vesamenu.c32 syslinux-${syslinux_ver}/${dirprefix}com32/chain/chain.c32 syslinux-${syslinux_ver}/${dirprefix}win32/syslinux.exe syslinux-${syslinux_ver}/${dirprefix}win64/syslinux64.exe syslinux-${syslinux_ver}/${dirprefix}linux/syslinux* syslinux-${syslinux_ver}/${dirprefix}extlinux/extlinux* syslinux-${syslinux_ver}/${dirprefix}mbr/mbr.bin syslinux-${syslinux_ver}/${dirprefix}core/isolinux.bin syslinux-${syslinux_ver}/${dirprefix}memdisk/memdisk $syslinux_extra_c32
   mv -f syslinux-${syslinux_ver}/${dirprefix}com32/menu/menu.c32 .
   mv -f syslinux-${syslinux_ver}/${dirprefix}com32/menu/vesamenu.c32 .
   mv -f syslinux-${syslinux_ver}/${dirprefix}com32/chain/chain.c32 .
   mv -f syslinux-${syslinux_ver}/${dirprefix}win32/syslinux.exe . 
   mv -f syslinux-${syslinux_ver}/${dirprefix}win64/syslinux64.exe . 
   mv -f syslinux-${syslinux_ver}/${dirprefix}mbr/mbr.bin .
   mv -f syslinux-${syslinux_ver}/${dirprefix}linux/syslinux .
   mv -f syslinux-${syslinux_ver}/${dirprefix}extlinux/extlinux .
   mv -f syslinux-${syslinux_ver}/${dirprefix}core/isolinux.bin .
   mv -f syslinux-${syslinux_ver}/${dirprefix}memdisk/memdisk .
   if [ -n "$syslinux_extra_c32" ]; then
      mv -f syslinux-${syslinux_ver}/${dirprefix}com32/elflink/ldlinux/ldlinux.c32 .
      mv -f syslinux-${syslinux_ver}/${dirprefix}com32/lib/libcom32.c32 .
      mv -f syslinux-${syslinux_ver}/${dirprefix}com32/libutil/libutil.c32 .
      chmod 644 *.c32
   fi
  )
  # For EFI machine
  if [ "$live_efi_boot_loader" = "syslinux" ]; then
    if [ -n "$dirprefix" ]; then
      # This means the downloaded syslinux support EFI (for version >=6.01), then we should prepare that, too. Here we only add efi64, since efi32 is not very common for modern machine.
      # Ref: http://www.rodsbooks.com/efi-bootloaders/syslinux.html especially the tarball http://www.rodsbooks.com/efi-bootloaders/syslinux-6.01.pre5-1.tgz
      syslinux_efi_coms="menu.c32 vesamenu.c32 ldlinux.c32 chain.c32 libutil.c32 libcom32.c32"
      # ./efi64/efi/syslinux.efi -> bootx64.efi
      # ./efi64/com32/elflink/ldlinux/ldlinux.e64
      mkdir -p $sysl_dir/efi/
      (
       cd $sysl_dir/efi/
       tar --wildcards -xvJf ../syslinux-${syslinux_ver}.tar.xz \
       syslinux-${syslinux_ver}/efi64/efi/syslinux.efi \
       syslinux-${syslinux_ver}/efi64/com32/elflink/ldlinux/ldlinux.e64 \
       syslinux-${syslinux_ver}/efi64/com32/menu/menu.c32 \
       syslinux-${syslinux_ver}/efi64/com32/menu/vesamenu.c32 \
       syslinux-${syslinux_ver}/efi64/com32/chain/chain.c32 \
       syslinux-${syslinux_ver}/efi64/com32/lib/libcom32.c32 \
       syslinux-${syslinux_ver}/efi64/com32/libutil/libutil.c32
    
       mv -f syslinux-${syslinux_ver}/efi64/efi/syslinux.efi bootx64.efi
       mv -f syslinux-${syslinux_ver}/efi64/com32/elflink/ldlinux/ldlinux.e64 .
       mv -f syslinux-${syslinux_ver}/efi64/com32/menu/menu.c32 .
       mv -f syslinux-${syslinux_ver}/efi64/com32/menu/vesamenu.c32 .
       mv -f syslinux-${syslinux_ver}/efi64/com32/chain/chain.c32 .
       mv -f syslinux-${syslinux_ver}/efi64/com32/lib/libcom32.c32 .
       mv -f syslinux-${syslinux_ver}/efi64/com32/libutil/libutil.c32 .
       chmod 644 ldlinux.e64 *.c32
      )
    fi
  fi
} # end of get_syslinux_binary_for_dos_linux
#
put_syslinux_makeboot_for_usb_flash() {
  local t_dir="$1"
  # syslinux_ver is not required. If it's not assigned, the latest one on the web will be used.
  local syslinux_ver="$2"  
  local sysl_dir sysl_extra_c32_chklist
  local latest_syslinux_v apt_tmpdir
  sysl_extra_c32_chklist="ldlinux.c32 libcom32.c32 libutil.c32"
  [ -z "$t_dir" -o ! -d "$t_dir" ] && echo "No t_dir!" && exit 1
  # Function to put syslinux.exe and syslinux (linux ELF 32-bit LSB executable) in dir t_dir 
  mkdir -p $t_dir/utils/{linux,win32,win64,mbr}
  mkdir -p $t_dir/utils/linux/{x86,x64}
  cp -a $pxelinux_binsrc_dir/makeboot.sh $t_dir/utils/linux/
  cp -a $pxelinux_binsrc_dir/makeboot.bat $t_dir/utils/win32/
  cp -a $pxelinux_binsrc_dir/makeboot64.cmd $t_dir/utils/win64/
  sysl_dir="$(mktemp -d /tmp/sysl_dir.XXXXXX)"
  get_syslinux_binary_for_dos_linux $sysl_dir $syslinux_ver
  # syslinux does not provide any option to find the version number.
  # Try to find the version of syslinux
  # Use strings to find the version, the output is like:
  # SYSLINUX 3.71 Debian-2008-08-04
  if [ -z "$syslinux_ver" ]; then
    SYSLINUX_VER="$(LC_ALL=C strings $sysl_dir/bios/syslinux | grep -iE "^SYSLINUX.*[[:digit:]]+" | awk -F" " '{print $2}')"
  else
    SYSLINUX_VER="$syslinux_ver"
  fi
  echo "SYSLINUX version: $SYSLINUX_VER" > $t_dir/utils/linux/VERSION.txt
  cp -a $t_dir/utils/linux/VERSION.txt $t_dir/utils/win32/
  cp -a $t_dir/utils/linux/VERSION.txt $t_dir/utils/win64/
  echo "Precompiled binary syslinux files were extracted from $syslinux_binsrc_url/syslinux-${syslinux_ver}.tar.xz" > $t_dir/utils/README.txt
  # For BIOS machine
  cp -af $sysl_dir/bios/{isolinux.bin,memdisk,menu.c32,vesamenu.c32,chain.c32} $t_dir/syslinux/
  # To make the version consistent, put them to isolinux dir, too.
  # Jan/19/2014 We have unified isolinux and syslinux dir as one dir syslinux only.
  # cp -af $sysl_dir/bios/{menu.c32,vesamenu.c32,chain.c32} $t_dir/isolinux/
  cp -af $sysl_dir/bios/syslinux.exe $t_dir/utils/win32/
  cp -af $sysl_dir/bios/syslinux64.exe $t_dir/utils/win64/
  cp -af $sysl_dir/bios/mbr.bin $t_dir/utils/mbr/
  for i in $sysl_extra_c32_chklist; do
    if [ -e $sysl_dir/bios/$i ]; then
      cp -af $sysl_dir/bios/$i $t_dir/syslinux/
      # To make the version consistent, put them to isolinux dir, too.
      # Jan/19/2014 We have unified isolinux and syslinux dir as one dir syslinux only.
      # cp -af $sysl_dir/bios/$i $t_dir/isolinux/
    fi
  done
  if [ -n "$(LC_ALL=C file $sysl_dir/bios/syslinux | grep -iEwo "ELF 32-bit")" ]; then
    cp -af $sysl_dir/bios/{syslinux,extlinux} $t_dir/utils/linux/x86
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "32-bit syslinux and extlinux not found!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
  if [ -n "$(LC_ALL=C file /usr/bin/syslinux | grep -iEwo "ELF 64-bit")" ]; then
    # If it's Debian, use better way to get the right version of syslinux and extlinux, and overwrite the ones from syslinux zip file
    check_distribution_name 
    if [ "$OS_type" = "DBN" ]; then
      # latest_syslinux_v is like: 3:6.03+dfsg-14.1+deb9u1
      apt-get update
      latest_syslinux_v="$(LC_ALL=C apt-cache show syslinux | grep -iE "^Version:" | grep -Ew "${SYSLINUX_VER}" | sort -V -r | head -n 1 | awk -F" " '{print $2}')"
      
      apt_tmpdir="$(mktemp -d /tmp/apt_deb.XXXXXX)"
      (
      cd $apt_tmpdir
      apt-get download syslinux:amd64=${latest_syslinux_v} syslinux-common:amd64=${latest_syslinux_v} extlinux:amd64=${latest_syslinux_v=} isolinux:amd64=${latest_syslinux_v=}
      # apt-get download syslinux:amd64 syslinux-common:amd64 extlinux:amd64 isolinux:amd64
      for ideb in $apt_tmpdir/*.deb; do
        dpkg -x $ideb $apt_tmpdir/
      done
      )
      cp -avf $apt_tmpdir/usr/bin/{syslinux,extlinux} $t_dir/utils/linux/x64/
      cp -avf $apt_tmpdir/usr/lib/syslinux/memdisk $t_dir/syslinux/
      cp -avf $apt_tmpdir/usr/lib/ISOLINUX/isolinux.bin $t_dir/syslinux/
      cp -avf $apt_tmpdir/usr/lib/syslinux/mbr/mbr.bin $t_dir/utils/mbr/
      c32_mod="chain.c32 ldlinux.c32 libcom32.c32 libutil.c32 menu.c32 vesamenu.c32"
      for i in $c32_mod; do
        cp -avf $apt_tmpdir/usr/lib/syslinux/modules/bios/$i $t_dir/syslinux/
      done
      if [ -n "$(echo $apt_tmpdir | grep -Ew "apt_deb")" ]; then
        rm -rf $apt_tmpdir
      fi
      (
      mkdir $apt_tmpdir; cd $apt_tmpdir
      # apt-get download syslinux:i386=${latest_syslinux_v} extlinux:i386=${latest_syslinux_v=} 
      apt-get download syslinux:i386 extlinux:i386 
      for ideb in $apt_tmpdir/*.deb; do
        dpkg -x $ideb $apt_tmpdir/
      done
      )
      # Only /usr/bin/{syslinux,extlinux}, for those *.c32 and other files, use those from amd64 deb.
      cp -avf $apt_tmpdir/usr/bin/{syslinux,extlinux} $t_dir/utils/linux/x86/
    else
      # Using the one from running AMD64 GNU/Linux. However, this might be different version from the downloaded syslinux zip file.
      cp -af /usr/bin/{syslinux,extlinux} $t_dir/utils/linux/x64
    fi
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "64-bit syslinux and extlinux not found in the dir /usr/bin/!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
  # For EFI machine
  if [ "$live_efi_boot_loader" = "syslinux" ]; then
    if [ -d "$sysl_dir/efi" ]; then
      mkdir -p $t_dir/EFI/boot/
      cp -af $sysl_dir/efi/bootx64.efi $t_dir/EFI/boot/
      cp -af $sysl_dir/efi/ldlinux.e64 $t_dir/EFI/boot/
      cp -af $sysl_dir/efi/*.c32 $t_dir/EFI/boot/
    fi
  fi
  [ -d "$sysl_dir" -a -n "$(echo $sysl_dir | grep "sysl_dir")" ] && rm -rf $sysl_dir
} # end of put_syslinux_makeboot_for_usb_flash
#
create_live_required_debian_based_prompt() {
  # lh_ver_required is global varible from drbl-ocs.conf
  local lh_ver debootstrap_ver
  # live-helper package name was changed to be live-build after 2.0~a20
  lh_ver="$(LC_ALL=C dpkg-query -W -f='${Version}\n' live-build)"
  if [ -z "$lh_ver" ]; then
    # Try to find the old package name.
    lh_ver="$(LC_ALL=C dpkg-query -W -f='${Version}\n' live-helper)"
  fi
  debootstrap_ver="$(LC_ALL=C debootstrap --version | grep -iEw "^debootstrap" | awk -F" " '{print $2}')"
  mmdebstrap_ver="$(LC_ALL=C mmdebstrap --version | grep -iEw "^mmdebstrap" | awk -F" " '{print $2}')"
  if dpkg --compare-versions "$lh_ver" "<<" "$lh_ver_required"; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "Required live helper or live build version: $lh_ver_required"
    echo "Installed live helper or live build version: $lh_ver"
    echo "You have to install patched live-helper or live-build (${lh_ver_required}drbl or later, modified by DRBL project)"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "Program terminated!"
    exit 1
  fi
  if dpkg --compare-versions "$debootstrap_ver" "<<" "$debootstrap_ver_required"; then
    if dpkg --compare-versions "$mmdebstrap_ver" "<<" "$mmdebstrap_ver_required"; then
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "Required debootstrap version: $debootstrap_ver_required"
      echo "Installed debootstrap version: $debootstrap_ver"
      echo "Required mmdebstrap version: $mmdebstrap_ver_required"
      echo "Installed mmdebstrap version: $mmdebstrap_ver"
      echo "You have to install debootstrap (version $debootstrap_ver_required or later) or mmdebstrap (verion $mmdebstrap_ver_required or later)."
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo "Program terminated!"
      exit 1
    fi
  fi
  if [ "$batch_mode" = "no" ]; then
    echo -n "Press enter to continue... "
    read
  fi
} # End of create_live_required_debian_based_prompt
#
turn_on_ipv4_forward() {
  # Making the rules stick and load on boot:
  if grep -q "^net.ipv4.ip_forward" /etc/sysctl.conf 2>/dev/null; then
    perl -p -i -e "s/^net.ipv4.ip_forward.*/net.ipv4.ip_forward = 1/" /etc/sysctl.conf
  else
    echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
  fi
  # Turn on ip_forward now.
  if [ "$(cat /proc/sys/net/ipv4/ip_forward)" != "1" ]; then
    echo "Turn on ip_forward now."
    echo 1 > /proc/sys/net/ipv4/ip_forward
  else 
    echo "ip_forward is already on."
  fi
} # end of turn_on_ipv4_forward
#
ask_if_beginner_or_expert_mode(){
  local TMP mode
  # ocs_user_mode is global variable
  TMP="$(mktemp /tmp/menu-ocs.XXXXXX)"
  trap "[ -f "$TMP" ] && rm -f $TMP" HUP INT QUIT TERM EXIT
  $DIA --backtitle "$msg_nchc_free_software_labs" --title  \
  "$msg_nchc_clonezilla" --menu "$msg_select_beginner_or_expert_mode:" \
  0 0 0 \
  "Beginner"  "$msg_beginner_mode" \
  "Expert"    "$msg_expert_mode" \
  "Exit"      "$msg_exit. $msg_enter_cml" \
  2> $TMP
  mode="$(cat $TMP)"
  [ -e "$TMP" ] && rm -f $TMP
  case "$mode" in
    "Beginner") ocs_user_mode="beginner" ;;
    "Expert")   ocs_user_mode="expert" ;;
    *)
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "$msg_program_stop!"
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      exit 1
  esac
} # end of ask_if_beginner_or_expert_mode
#
rep_whspc_w_udrsc() {
  # Function to replace white space as "_", so in dialog we won't make it as 2 or more tags or items.
  local inp_txt="$1"
  local out_txt
  out_txt="$(echo ${inp_txt} | sed -r -e "s/[[:space:]]/_/g")"
  echo "$out_txt"
} # end of rep_whspc_w_udrsc
#
# Function copy_exec_drbl is borrowed from copy_exec from Debian's package initramfs-tools: /usr/share/initramfs-tools/hook-functions. The difference is that we use "cp -pL" instead of "ln -fs" in this function. This is because when we run mkpxeinitrd-net, we run cpio without "--dereference" (mkinitramfs uses cpio with "--dereference"), i.e. in mkpxeinitrd-net, we use:
 # find . | cpio --quiet -o -H newc | gzip -9 > $output_dir/initrd-$initrd_suffix.$kernel_ver.img )
 # instead of
 # find . | cpio --quiet --dereference -o -H newc | gzip -9 > $output_dir/initrd-$initrd_suffix.$kernel_ver.img )
 # The reason to do so is we use symbolic link to link the command to busybox in/usr/lib/mkpxeinitrd-net/initrd-skel/bin/. If we use --dereference, it will take a lot of space. This might be improved in the future.
 
# $1 is the source path (e.g. /usr/bin/time)
# $2 is the relative destination (e.g. /usr or /usr/time)
#
# The destination is interpreted in the same way "cp" would, meaning
# (assuming /bin is a directory):
#
#   "copy_exec_drbl /usr/bin/time /bin"        -> /bin/time
#   "copy_exec_drbl /usr/bin/time /bin/mytime" -> /bin/mytime
# 
# If $2 is left out, the same destination path as for the source arg will
# be used and directories will be created as needed, so:
#
#   "copy_exec_drbl /usr/bin/time"             -> /usr/bin/time
#
copy_exec_drbl() {
  local source target destination final_destination x nonoptlib
  local libname dirname
  
  source="${1}"
  if [ -n "${2}" ]; then
  	if [ ! -d "${DESTDIR}/${2}" ]; then
  		mkdir -p "${DESTDIR}/${2}"
  	fi
  	target="${2}"
  else
  	if [ ! -e "${DESTDIR}/$(dirname "${1}")" ]; then
  		mkdir -p "${DESTDIR}/$(dirname "${1}")"
  	fi
  	target="${1}"
  fi
  
  if [ -d "${DESTDIR}/${target}" ]; then
  	destination="${target}/$(basename "${source}")"
  else
  	destination="${target}"
  fi
  final_destination="${DESTDIR}/${destination}"
  
  if [ -L "$final_destination" ]; then
  	if [ $(readlink "${final_destination}") != "${source}" ]; then
  	  #	echo "W:copy_exec_drbl: Not copying ${source} to \$DESTDIR${destination}, which is already a copy of $(readlink ${final_destination})" >&2
  		return
  	fi
  else
  	cp -pL ${source} ${DESTDIR}/${destination}
  	if [ "${verbose}" = "y" ]; then
  		echo "Adding binary ${source}"
  	fi
  fi
  
  # Copy the dependant libraries
  for x in $(ldd ${source} 2>/dev/null | sed -e '
      /\//!d;
      /linux-gate/d;
      /=>/ {s/.*=>[[:blank:]]*\([^[:blank:]]*\).*/\1/};
      s/[[:blank:]]*\([^[:blank:]]*\) (.*)/\1/' 2>/dev/null); do
  
  	# Try to use non-optimised libraries where possible.
  	# We assume that all HWCAP libraries will be in tls,
  	# sse2, vfp or neon
  	nonoptlib=$(echo "${x}" | sed -e 's#/lib/\(tls\|i686\|sse2\|neon\|vfp\).*/\(lib.*\)#/lib/\2#')
  
  	if [ -e "${nonoptlib}" ]; then
  		x="${nonoptlib}"
  	fi
  
  	libname=$(basename "${x}")
  	dirname=$(dirname "${x}")
  
  	mkdir -p "${DESTDIR}/${dirname}"
  	if [ ! -e "${DESTDIR}/${dirname}/${libname}" ]; then
  		cp -pL "${x}" "${DESTDIR}/${dirname}"
  		if [ "${verbose}" = "y" ]; then
  			echo "Adding library ${x}"
  		fi
  	fi
  done
} # end of copy_exec_drbl
#
get_block_line_in_upstart_conf() {
  local CFG_FILE="$1"
  local comment_status="$2"
  local comment
  [ -e "$CFG_FILE" ] || exit 1
  # There are 2 types of init config:
  # (1)
  #    start on filesystem
  # (2)
  #    start on (local-filesystems
  #              and net-device-up IFACE=lo)
  # Wen can judge them by: grep -n -E "^start on[[:space:]]+\(" $CFG_FILE
  # Take /etc/init/gdm.conf as an example:
  # start on (filesystem
  # 	  and started hal
  # 	  and tty-device-added KERNEL=tty7
  # 	  and (graphics-device-added or stopped udevtrigger))
  # By using:
  # grep -n -E "^start on[[:space:]]+\(" gdm.conf
  # We can get the results like:
  # ------------
  # 9:start on (filesystem
  # ------------
  # grep -n -E -A 1000 "^start on[[:space:]]+\(" gdm.conf  | grep -E  "\)" | head -n 1
  # We can get the results like:
  # ------------
  # 12-       and (graphics-device-added or stopped udevtrigger))
  # ------------
  # so we know we can replace the one between line no. 9 and 12
  if [ "$comment_status" = "commented" ]; then
    comment="#"
  else
    comment=""
  fi
  if [ -z "$(LC_ALL=C grep -n -E "^${comment}[[:space:]]*start on[[:space:]]+\(" $CFG_FILE)" ]; then
    # Type 1
    begin_line="$(LC_ALL=C grep -n -E "^${comment}[[:space:]]*start on[[:space:]]+" $CFG_FILE | cut -d":" -f1)"
    end_line="${begin_line}"
  else
    # Type 2
    begin_line="$(LC_ALL=C grep -n -E "^${comment}[[:space:]]*start on[[:space:]]+\(" $CFG_FILE | cut -d":" -f1)"
    end_line="$(LC_ALL=C grep -n -E -A 1000 "^${comment}[[:space:]]*start on[[:space:]]+\(" $CFG_FILE | grep -E  "\)" | head -n 1 | cut -d "-" -f1)"
  fi
  echo "$begin_line $end_line"
} # end of get_block_line_in_upstart_conf
#
switch_upstart_service() {
  # The function to comment or uncomment the upstart /etc/init/*.conf 	 
  local CFG_F="$1"
  local mod_want="$2"  # "on" or "off"
  [ -z "$CFG_F" ] && "No 'CFG_F' assigned in function switch_upstart_service!" && exit 1
  [ -z "$mod_want" ] && "No 'mod_want' assigned in function switch_upstart_service!" && exit 1
  [ -e /etc/lsb-release ] && . /etc/lsb-release
  if [ "$DISTRIB_RELEASE" \< 13.10 ]; then
    # Ubuntu < 13.10
    # # Just edit the config file directly, so that it's could only be started manually. We can NOT just rename the *.conf. Otherwise the service can not be started manually in drbl-client-boot.conf.
    # If we want to turn on the service, the status now should be commented.
    case "$mod_want" in
     on)  status="commented";;
     off) status="not_commented";;
    esac
    lines="$(get_block_line_in_upstart_conf $CFG_F $status)"
    begin_line="$(echo $lines | awk -F" " '{print $1}')"
    end_line="$(echo $lines | awk -F" " '{print $2}')"
    case "$mod_want" in
     off) sub_cmd="if ($((begin_line))..$((end_line))) {s/^(.*)$/# \$1 # Modified by DRBL/g}" ;;
     on)  sub_cmd="if ($((begin_line))..$((end_line))) {s/^#[[:space:]]?(.*)$/\$1/g}" ;;
    esac
    perl -pi -e "$sub_cmd" $CFG_F

    # XXXXXXXXXXXXXXXXXXX This is wrong! If doing this, some required service could not be manually started in drbl-client-boot.conf.
    #case "$mod_want" in
    #  off) 
    #       if [ -e "${CFG_F}" ]; then
    #         mv ${CFG_F} ${CFG_F}.drbl-disabled
    #       fi
    #       ;;
    #  on)  
    #       if [ -e "${CFG_F}.drbl-disabled" ]; then
    #         mv ${CFG_F}.drbl-disabled ${CFG_F}
    #       fi
    #       ;;
    #esac
  else
    # Ubuntu 13.10 or later.
    # For upstart (>1.3) service, we can use override file (Ref: http://upstart.ubuntu.com/cookbook/#override-files)
    case "$mod_want" in
      off) echo "manual" > ${CFG_F/.conf/}.override;;
      on)  rm -f ${CFG_F/.conf/}.override;;
    esac
  fi
} # end of switch_upstart_service
#
canonical_hostname_prep() {
  # This function is used to avoid the bug of nfs-utils 1.2.2-1:
  # statd wont't work without reverse lookups. Therefore lockd will fail.
  # Ref: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=579397
  # The problem is not only on the server side, but also on the client side.
  local nfs_srv="$1"
  if ! host "$nfs_srv" &>/dev/null && \
     [ -z "$(LC_ALL=C  grep -Ew "^[[:space:]]*$nfs_srv" /etc/hosts )" ]; then
    echo "# Dummy NFS server lookup to avoid NFS statd/lockd issue. Created by Clonezilla." >> /etc/hosts
    echo "$nfs_srv nfs-server" >> /etc/hosts
  fi
} # end of canonical_hostname_prep
#
get_debian_ubuntu_init_serv_control_prog() {
  # Find to use update-rc.d or insserv in Debian or Ubuntu
  # dbn_ubn_serv_control_prog is global value
  [ -e /etc/lsb-release ] && . /etc/lsb-release
  dbn_ubn_serv_control_prog=""
  if [ "$DISTRIB_ID" = "Ubuntu" ]; then
     # Ubuntu, do not use insserv, otherwise it might confuse upstart and traditional rc
     dbn_ubn_serv_control_prog="use-update-rc-d"
  else
     # Debian, we check if insserv exists or not.
     if type insserv &>/dev/null; then
       dbn_ubn_serv_control_prog="use-insserv"
     else
       dbn_ubn_serv_control_prog="use-update-rc-d"
     fi
  fi
} # end of get_debian_ubuntu_init_serv_control_prog
#
get_sort_V_opt() {
  # A function to get if the "-V" option is supported on the system. This is because old version of sort does not support the option "-V", but newer one does.
  # Variable "sort_V_opt" is global variable.
  if [ -n "$(LC_ALL=C sort --help 2>&1 | grep -i -- "--version-sort")" ]; then
    # Check if version sorting option is supported. If so, use it.
    sort_V_opt="-V"
  fi
} # get_sort_V_opt
#
disable_apt_lang_translation() {
  local lang_cf_file="$1" # e.g. chroot/etc/apt/apt.conf.d/99lang
  if [ -z "$lang_cf_file" ]; then
    echo "No \"lang_cf_file\" in function disable_apt_lang_translation!"
    exit 1
  fi
  mkdir -p $(dirname $lang_cf_file)
  cat <<-APT_END > $lang_cf_file
Acquire
{
  Retries "0";
        Languages "none";
        Translation "none";
};
APT_END
} # end of disable_apt_lang_translation
#
get_latest_pkg_in_drbl_repository() {
  local branch pkg ktmp
  # pver is global variabl
  branch="$1" # e.g. live-experimental, unstable...
  pkg="$2"  # e.g. live-boot
  if [ -z "$branch" ]; then
    echo "No \$branch in function get_latest_pkg_in_repository!"
    exit 1
  fi
  if [ -z "$pkg" ]; then
    echo "No \$pkg in function get_latest_pkg_in_repository!"
    exit 1
  fi
  ktmp="$(mktemp -d /tmp/live_pver.XXXXXX || exit 1)"
    echo "Downloading $drbl_mirror_url/dists/drbl/$branch/binary-amd64/Packages.xz to finding latest $pkg version..."
    LC_ALL=C wget -q -P $ktmp/ $drbl_mirror_url/dists/drbl/$branch/binary-amd64/Packages.xz
    # The versions might be with epoch like:
    # 4.0.2-1.drbl15
    # 1:20170623.drbl1
    # Hence we add all of them as:
    # 0:4.0.2-1.drbl15
    # 1:20170623.drbl1
    pver="$(xzgrep -Ew -A 5 "^Package: $pkg([[:space:]]+|$)" $ktmp/Packages.xz | grep -E "^Version:" | sed -e "s/^Version: //g" | sed -r -e "s/^([^:]+)$/0:\1/g" | sort -V -r | uniq | head -n 1)"
    if [ -z "$pver" ]; then
      # Clean Packages.xz to avoid wget using another name like Packages.xz.1 then search the next again
      rm -f $ktmp/Packages.xz
      return 1
    fi
  if [ -n "$pver" ]; then
    # After the comparison is done, we have to change it back, i.e.,
    # 0:4.0.2-1.drbl15 -> 4.0.2-1.drbl15
    pver="$(echo $pver | sed -r -e "s/^0://g")"
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Warning!"
    echo "Unable to find the latest package version in $drbl_mirror_url/dists/$i/main/binary-amd64/Packages.xz."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "$msg_press_enter_to_continue"
    read 
  fi
  [ -d "$ktmp" -a -n "$(echo $ktmp | grep "live_pver")" ] && rm -rf $ktmp
  return 0
} # end of get_latest_pkg_in_drbl_repository
#
gen_CDG_checksums() {
  # This function will generate Clonezilla, DRBL, GParted live checksum files, including MD5SUMS, SHA1SUMS, and a file called CHECKSUMS.TXT including MD5 and SHA1 checksums.
  local sum_file="CHECKSUMS.TXT"
  local sum_file_html="CHECKSUMS.php"
  local filetype="iso zip tar tar.gz"
  local sum_types="md5sum sha1sum sha256sum sha512sum b2sum b3sum"
  local sum_of
  echo -n "Creating checksums..."
  rm -f $sum_file $sum_file_html
  for jsum in $sum_types; do
    sum_of="$(echo $jsum | tr "[a-z]" "[A-Z]")S"  # e.g. md5sum -> MD5SUMS
    [ -e "$sum_of" ] && rm -f $sum_of
    for i in $filetype; do
      if [ -n "$(ls *.$i 2>/dev/null)" ]; then
        echo -n "."
        LC_ALL=C $jsum *.$i  >> $sum_of
      fi
    done
    echo "### ${sum_of}:" >> $sum_file
    cat ${sum_of} >> $sum_file
    echo >> $sum_file
  done
  echo " Done!"

  txt2html $sum_file > $sum_file_html
} # end of gen_CDG_checksums
#
find_next_release_version_number() {
  # Function to find the next release number in dir "$release_dir". This is used only for creating Clonezilla/DRBL/GParted live.
  local release_dir="$1"
  local next_v_major next_v_minor next_v_full
  # Default release dir is "release"
  [ -z "$release_dir" ] && release_dir="release"  
  # The dirs in release dir are like:
  # 2.0.0-28/
  # 2.0.0-29/
  # 2.0.0-30/
  # zip-dest/
  # zip-src/
  # Find the last version, i.e. 2.0.0-30
  version_now="$(LC_ALL=C find ./$release_dir/ -maxdepth 1 -type d -print 2>/dev/null | awk -F"/" '{print $3}' | grep -E "^[[:digit:]].*" | sort -r -V | uniq | head -n 1)"
  # Increase the minor # (i.e. 30) by 1
  if [ -n "$version_now" ]; then
    next_v_major="$(LC_ALL=C echo "$version_now" | awk -F "-" '{print $1}')"
    next_v_minor="$(LC_ALL=C echo "$version_now" | awk -F "-" '{print $2}')"
    next_v_minor="$((next_v_minor + 1))"
    next_v_full="$next_v_major-$next_v_minor"
  fi
  if [ -n "$next_v_major" -a -n "$next_v_minor" ]; then
    echo "$next_v_full"
    return 0
  else
    return 1
  fi
} # end of find_next_release_version_number
#
restore_lvm2_udevd_rules() {
  local new_fname reload_flag=false
  # Restore the udevd rules, which are disabled by ocs-lvm2-stop.
  echo "Checking if udevd rules have to be restored..."
  for i in /lib/udev/rules.d/*.drblsave; do
    [ ! -e "$i" ] && continue
    new_fname="$(echo $i | sed -r -e "s/\.drblsave$//g")"
    mv -v "$i" "$new_fname"
    reload_flag="true"
  done
  # Reload the rules for udevd
  if [ "$reload_flag" = "true" ]; then
    echo "Running 'udevadm control --reload-rules' to reload udevd rules..."
    udevadm control --reload-rules
  fi
} # End of restore_lvm2_udevd_rules

#
disable_lvm2_udevd_rules() {
  local node_rt="$1"  # E.g. /tftpboot/node_root/. If $node_rt is not assigned, it's for the running system. E.g. Clonezilla live. If assigned, it's for Clonezilla SE used normally.
  # 2012/Nov/20 Ubuntu's lvm2 has a udevd rules will automatically active VG, therefore before using "vgchange -an" to deactive the VG, we have to disable it, then restore it later.
  auto_active_rules="$(LC_ALL=C grep -Ew "^[^#].*vgchange -a y" $node_rt/lib/udev/rules.d/*.rules 2>/dev/null | awk -F":" '{print $1}')"
  if [ -n "$auto_active_rules" ]; then
    echo "Found udevd rule causes block devices with LVM signatures to be automatically added to their volume group."
    echo "Temporarily disable it otherwise the partition tool won't be able to inform the kernel the changes of partition table..."
    for i in $auto_active_rules; do
      mv -v "${i}" "${i}.drblsave"
    done
    # Reload the rules for udevd for running system, i.e. Clonezilla live. For Clonezilla SE, since it's in /tftpboot/node_root/, during the booting it won't be started.
    if [ -z "$node_rt" ]; then
      udevadm control --reload-rules
    fi
  fi
} # end of disable_lvm2_udevd_rules
#
is_systemd_init() {
  # Function to test if system is really using systemd by checking if /sbin/init is link to /lib/systemd/systemd.
  local real_init re_code
  if [ -x "/bin/systemctl" -a -d "/lib/systemd/system/" ]; then
    real_init="$(LC_ALL=C stat -c "%N" /sbin/init | awk -F"->" '{print $2}' | sed -r -e "s/^[[:space:]]*//g" -e "s/\`//g" -e "s/'//g")"
    if [ -n "$real_init" ]; then
      if [ "$(LC_ALL=C basename $real_init)" = "systemd" ]; then
        re_code=0
      else
        re_code=1
      fi
    else
      re_code=1
    fi
  else
    re_code=1
  fi
  return $re_code
} # end of is_systemd_init
#
check_if_system_support_ecryptfs(){
  local rc
  # Not really. It might be bulit-in
  # So let's check /proc/filesystems
  modprobe ecryptfs 2>/dev/null
  sleep 1
  if ! grep -Ewq "ecryptfs" /proc/filesystems; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "File system \"ecryptfs\" is not supported by the running Linux kernel \"`uname -r`\"" | tee --append ${OCS_LOGFILE}
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop." | tee --append ${OCS_LOGFILE}
    grand_jobs_before_exit
    exit 1
  fi
  if ! type mount.ecryptfs &>/dev/null; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "No \"ecryptfs\" related program was found on this system." | tee --append ${OCS_LOGFILE}
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop." | tee --append ${OCS_LOGFILE}
    my_ocs_exit 1
  fi
} # end of check_if_system_support_ecryptfs
#
task_ecryptfs_mount_point() {
  local task_type="$1"
  local pass1 pass2 ecryptfs_pf
  local TMP grc rc ask_ ans_ rc_bindfs ocs_ecryptfs_opt
  local enc_cmd_
  # ecrypt_mntpnt, bindfs_mntpnt, webdav_bindfs_flag, target_dir_orig and
  # target_dir, passwd_ecryptfs and passwd_file_ecryptfs are gloable variables.
  # Change the ocsroot to /tmp now since we will create the mount point in /tmp

  if `is_s3fs_ocsroot` || `is_cloudfuse_ocsroot`; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "Using ecryptfs with s3fs or cloudfuse has an issue." | tee --append ${OCS_LOGFILE}
    echo "Please check this URL for more info:" | tee --append ${OCS_LOGFILE}
    echo "https://github.com/s3fs-fuse/s3fs-fuse/issues/166" | tee --append ${OCS_LOGFILE}
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop!" | tee --append ${OCS_LOGFILE}
    exit 1
  fi
  check_if_system_support_ecryptfs
  # Define the ecryptfs option
  ocs_ecryptfs_opt="ecryptfs_cipher=$ocs_ecryptfs_cipher,ecryptfs_key_bytes=$ocs_ecryptfs_key_bytes,no_sig_cache,ecryptfs_enable_filename_crypto=n,ecryptfs_passthrough"
  ###
  ecrypt_mntpnt="$(mktemp -d /tmp/ecryptfs_mnt.XXXXXX)"
  ecryptfs_pf=$(mktemp /tmp/ecryptfs_f.XXXXXX)
  # Force to set the mode
  chmod 600 $ecryptfs_pf
  TMP=$(mktemp /tmp/ecryptfs_tmp.XXXXXX)
  trap "[ -f "$TMP" ] && rm -f $TMP" HUP INT QUIT TERM EXIT
  grc="1" # grand rc for the really working return code
  # Collect the password for ecryptfs. This is because for ecryptfs it only 
  # ask once, no confirmation.

  while [ "$grc" -ne 0 ]; do
    if [ -z "$passwd_ecryptfs" -a -z "$passwd_file_ecryptfs" ]; then
      # Not spedified by user. Ask passwd_ecryptfs
      rc="1"
      echo $msg_delimiter_star_line | tee --append ${OCS_LOGFILE}
      case "$task_type" in
       *save*) 
              # For saving, we ask twice.
              [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING | tee --append ${OCS_LOGFILE}
  	    echo "$msg_remember_passphrase_of_ecryptfs" | tee --append ${OCS_LOGFILE}
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL | tee --append ${OCS_LOGFILE}
  	    echo -e "*** $msg_enter_passphrase_to_encrypt_img: ${target_dir} ***\n($msg_it_will_not_be_echoed)" | tee --append ${OCS_LOGFILE}
              read -s pass1
  	    echo -e "*** $msg_reenter_passphrase_to_encrypt_img: ${target_dir} ***\n($msg_it_will_not_be_echoed)" | tee --append ${OCS_LOGFILE}
              read -s pass2
              while [ "$pass1" != "$pass2" ]; do
                [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
                echo "$msg_passphrases_not_match" | tee --append ${OCS_LOGFILE}
                [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  	      echo -e "*** $msg_enter_passphrase_to_encrypt_img: ${target_dir} ***\n($msg_it_will_not_be_echoed)" | tee --append ${OCS_LOGFILE}
                read -s pass1
  	      echo -e "*** $msg_reenter_passphrase_to_encrypt_img: ${target_dir} ***\n($msg_it_will_not_be_echoed)" | tee --append ${OCS_LOGFILE}
                read -s pass2
              done
              if [ -z "$pass1" ]; then
                [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  	        echo "$msg_passphrase_empty" | tee --append ${OCS_LOGFILE}
                [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
                echo "$msg_program_stop!" | tee --append ${OCS_LOGFILE}
  	        my_ocs_exit 1
              fi
              # set the matched passphrase
              passwd_ecryptfs="$pass1"
              ;;
          *)
              # For restoring, we ask once only.
  	    echo -e "*** $msg_enter_passphrase_for_decrypt_img: ${target_dir} ***\n($msg_it_will_not_be_echoed)" | tee --append ${OCS_LOGFILE}
              read -s passwd_ecryptfs
              ;;
      esac
    fi
    # Now at least there is passwd_ecryptfs or passwd_file_ecryptfs
    if [ -n "$passwd_ecryptfs" ]; then
      # Put it in the file
      echo "passphrase_passwd=$passwd_ecryptfs" > $ecryptfs_pf
    elif [ -e "$passwd_file_ecryptfs" ]; then
      cat $passwd_file_ecryptfs > $ecryptfs_pf
    else
      [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
      echo "Not password for ecryptfs was inputted or assigned in a file." | tee --append ${OCS_LOGFILE}
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      echo "$msg_program_stop!" | tee --append ${OCS_LOGFILE}
      my_ocs_exit 1
    fi

    #
    webdav_bindfs_flag="no"
    ask_="true"
    #
    while [ "$ask_" = "true" ]; do
      # If ocsroot is webdav, we have to use bindfs as the middle layer.
      # Reason: eCryptFS belongs to a class of pseudo-filesystems, i.e. file systems that run on top of a layer of conventional FS. But davfs2 refers to the network stack-based file systems that are not compatible with eCryptFS. Therefore it is necessary to use fs-wrapper - bindfs. It will hide all incompatibilities though cause some inconvenience.
      # Ref: http://www.linux.org.ru/wiki/en/WebDav%2Be%D0%A1ryptFS
      #      https://bugs.launchpad.net/ecryptfs/+bug/277578/comments/25
      if `is_davfs_ocsroot`; then
        bindfs_mntpnt="$(mktemp -d /tmp/bindfs_mnt.XXXXXX)"
	bindfs "$ocsroot/${target_dir}" $bindfs_mntpnt
	rc_bindfs="$?"
	if [ "$rc_bindfs" -eq 0 ]; then
          webdav_bindfs_flag="yes"
	  enc_cmd_="LC_ALL=C mount -t ecryptfs $bindfs_mntpnt $ecrypt_mntpnt -o $ocs_ecryptfs_opt,key=passphrase:passphrase_passwd_file=$ecryptfs_pf"
	  echo "Running: $enc_cmd_"
	  eval $enc_cmd_
          rc="$?"
        else
          [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
          echo "Failed to bindfs WebDAV image by:" | tee --append ${OCS_LOGFILE}
	  echo "bindfs \"$ocsroot/${target_dir}\" $bindfs_mntpnt" | tee --append ${OCS_LOGFILE}
          [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
          echo "$msg_program_stop" | tee --append ${OCS_LOGFILE}
          [ "$save_restore_error_log" = "yes" ] && copy_error_log
          exit 1
        fi
      else
        enc_cmd_="LC_ALL=C mount -t ecryptfs \"$ocsroot/${target_dir}\" \"$ecrypt_mntpnt\" -o $ocs_ecryptfs_opt,key=passphrase:passphrase_passwd_file=$ecryptfs_pf"
	echo "Running: $enc_cmd_"
	eval $enc_cmd_
        rc="$?"
      fi
      # Even wrong passphrase could give rc=0. However, the data are not really
      # decrypted. Therefore we have to use another method to check.
      if [ "$rc" -ne 0 ]; then
        # Pause so that user can read the error message
        echo -n "$msg_press_enter_to_continue..."
        read
        $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla" \
        --yesno "$msg_failed_to_encrypt_img\n$msg_do_u_want_to_do_it_again" 0 0
        ans_="$?"
        case "$ans_" in
          0) # yes is chosen
             ask_="true";;
          1) # no is chosen
             echo "$msg_program_stop!" | tee --append ${OCS_LOGFILE}
             [ -f "$TMP" ] && rm -f $TMP
             [ -f "$ecryptfs_pf" ] && rm -f $ecryptfs_pf
             my_ocs_exit 1;;
        esac
      else
        # Got the one we want
        ask_="false"
        # Do not keep the file on system. For security.
        [ -f "$ecryptfs_pf" ] && rm -f $ecryptfs_pf
      fi
    done
    if [ -z "$(echo "$task_type" | grep -e "save")" ]; then
      # Image exists already.
      # Check if the image really decrypted correctly by testing file "clonezilla-img". This is only for restoring
      # The results of "file -Lbi clonezilla-img" might be charset=utf-8 or us-ascii, or even others. Therefore just check it not binary and grep a line.
      if [ -z "$(LC_ALL=C file -Lbi "${ecrypt_mntpnt}/clonezilla-img" | grep -Ew "charset=binary")" -a \
           -n "$(grep -e "^This image was saved by Clonezilla" "${ecrypt_mntpnt}/clonezilla-img")" ]; then 		   
        grc=0
        [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
        echo "$msg_succeed_to_decrypt_img: ${target_dir}" | tee -a $OCS_LOGFILE
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        echo $msg_delimiter_star_line | tee -a $OCS_LOGFILE
      else
        [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
        echo "$msg_failed_to_decrypt_img: ${target_dir} " | tee -a $OCS_LOGFILE
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
	umount $ecrypt_mntpnt
	if [ "$webdav_bindfs_flag" = "yes" ]; then
	  umount $bindfs_mntpnt 2>/dev/null
        fi
        grc=1
        confirm_continue_or_not_default_continue
	# Reset the value passwd_ecryptfs and passwd_file_ecryptfs so user can input it again
	passwd_ecryptfs=""
	passwd_file_ecryptfs=""
      fi
    else
      # For saving task, the return code for "mount -t ecryptfs" can be used.
      # Since the above while loop is done, it means monting is OK now.
      grc=0
    fi
  done
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_encrypt_img_dir_is_now_as: ${ecrypt_mntpnt}" | tee -a $OCS_LOGFILE
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  if [ "$ocs_sr_mode" = "interactive" ]; then
    sleep 3
  fi
  # Save the original ocsroot for later use
  ocsroot_orig="$ocsroot"
  ocsroot="$(dirname ${ecrypt_mntpnt})"
  # Save the original image dir for later use
  target_dir_orig="${target_dir}"
  target_dir="$(basename "${ecrypt_mntpnt}")"
  #
  [ -f "$TMP" ] && rm -f $TMP
  return $grc
} # end of task_ecryptfs_mount_point
#
umount_ecryptfs_mount_point_if_necessary(){
  local rc rc_bindfs
  if [ "$encrypt_ocs_img" = "yes" ]; then
    if [ -n "$ecrypt_mntpnt" ]; then
      umount $ecrypt_mntpnt 2>/dev/null
      rc=$?
      if [ "$rc" -eq 0 ]; then
        if [ -d "$ecrypt_mntpnt" -a \
             -n "$(echo "$ecrypt_mntpnt" | grep -w "ecryptfs_mnt")" ]; then
	  # It's just a mounting point. Better not to use "rm -rf" in case wrongly remove all the dir.
          rmdir "$ecrypt_mntpnt"
        fi
      fi
      if [ "$webdav_bindfs_flag" = "yes" ]; then
        umount $bindfs_mntpnt 2>/dev/null
        rc_bindfs=$?
        if [ -d "$bindfs_mntpnt" -a \
             -n "$(echo "$bindfs_mntpnt" | grep -w "bindfs_mnt")" ]; then
	  # It's just a mounting point. Better not to use "rm -rf" in case wrongly remove all the dir.
          rmdir "$bindfs_mntpnt"
        fi
      fi
    fi
  fi
} # end of umount_ecryptfs_mount_point_if_necessary
#
is_ecryptfs_img() {
  local tgt_dir rc_enc
  tgt_dir_abs="$1"  # absolute path
  rc_enc="1"
   if [ -e "${tgt_dir_abs}/ecryptfs.info" ] && \
      [ -n "$(LC_ALL=C file -Lbi "${tgt_dir_abs}/clonezilla-img" | grep -Ew "charset=binary")" ]; then 		   
     rc_enc="0"
   fi
   return $rc_enc
} # end of is_ecryptfs_img
#
grand_jobs_before_exit() {
  # This function is used to collect the jobs before program aborting.
  # Including:
  # (1) Unmount ecryptfs if it exists.
  # (2) Remove MULTIPATH_INFODIR temp dir.
  # (3) Remove partition_table from gen_proc_partitions_map_file

  #(1)
  umount_ecryptfs_mount_point_if_necessary

  #(2)
  if [ -d "$MULTIPATH_INFODIR" -a \
       -n "$(echo $MULTIPATH_INFODIR | grep -w "multipath_info")" ]; then
    rm -f "$MULTIPATH_INFODIR/*"
    rmdir $MULTIPATH_INFODIR
  fi
  #(3)
  if [ -f "$partition_table" -a \
       -n "$(echo $partition_table | grep -w "parttable-ocs")" ]; then
    rm -f $partition_table
  fi
} # end of grand_jobs_before_exit
#
my_ocs_exit() {
  local ec="$1"
  grand_jobs_before_exit
  exit $ec
} # end of my_ocs_exit
#
drbl_service_ctl() {
  # Function to start/stop service, for systemd or sysv/upstart
  local srv_name="$1"
  local srv_action="$2"  # start, stop, and restart only
  if [ -n "$srv_name" -a -n "$srv_action" ]; then
    if is_systemd_init && [ -e "/lib/systemd/system/${srv_name}.service" ]; then
      systemctl $srv_action $srv_name
    else
      service $srv_name $srv_action
    fi
  fi
} # end of drbl_service_ctl
#
get_grub_efi_image_block() {
  local IMG_NAME="$1"
  local GRUB_CONF_TMP="$2"
  [ -z "$IMG_NAME" ] && exit 1
  # By using
  # grep -Ei -n '^[[:space:]]*menuentry[[:space:]]+.*([[:space:]]|$)+' /tftpboot/nbi_img/grub/grub.cfg | grep -A1 -E "menuentry[[:space:]]+.*--id drbl-client([[:space:]]|$)+"
  # 29:menuentry "CentOS 7.1.1503 Linux (DRBL mode, mostly local resources)" {
  # 34:menuentry 'Clonezilla' {
  # so we know we can replace the one between line no. 29 and 34
  if [ -n "$GRUB_CONF_TMP" -a ! -e "$GRUB_CONF_TMP" ]; then
    return 2
  fi
  between_lines="$(LC_ALL=C grep -Ei -n -- "^[[:space:]]*[#]*menuentry[[:space:]]+.*([[:space:]]|$)+" $GRUB_CONF_TMP | grep -Ei -A1 -- "menuentry[[:space:]]+.*$IMG_NAME([[:space:]]|$)+" | cut -d":" -f1)"
  begin_line="$(LC_ALL=C echo $between_lines | awk -F" " '{print $1}')"
  end_line="$(LC_ALL=C echo $between_lines | awk -F" " '{print $2}')"
  # if end_line is nothing, it must be the last block, i.e. we can not find the next [.*]
  if [ -z "$end_line" ]; then
    end_line="$(LC_ALL=C wc -l $GRUB_CONF_TMP | awk -F" " '{print $1}')"
  else
    # if not nothing, backword one line
    end_line="$(($end_line - 1))"
  fi
  echo "$begin_line $end_line"
} # end of get_grub_efi_image_block
#
set_specific_host_grub_efi_conf() {
  local HOSTS="$*"
  local grub_eficfg grub_eficfg_MAC grub_eficfg_MIP OCS_TMP IP
  # prepare the HOSTNAME-IP-MAC table
  OCS_TMP=`mktemp /tmp/ocs_clean_tmp.XXXXXX`
  trap "[ -f "$OCS_TMP" ] && rm -f $OCS_TMP" HUP INT QUIT TERM EXIT
  parse_dhcpd_conf $OCS_TMP

  for ih in $HOSTS; do
    case "$ih" in
      *.*.*.*)
        # list by IP
	# the grub_eficfg will like "grub.cfg-drbl-192.168.177.2"
	grub_eficfg="grub.cfg-drbl-${ih}"
        # These files look like: grub.cfg-drbl:$MAC, e.g., grub.cfg-drbl-88:aa:bb:cc:dd:ee
	# We'd better to clean the grub.cfg-drbl:$MAC if it exists since maybe it's created by ocsmgrd when received the results from client in the previous save/restoration. Since grub.cfg-drbl:$MAC has higher priority than "C0A80001" style file in pxelinux, this is a must if we can find it, we have to remove it.
	# TODO: What if no MAC address setting in dhcpd.conf ? Then $OCS_TMP will be empty, then... ?
        grub_eficfg_MAC="grub.cfg-drbl-$(grep ${ih} $OCS_TMP | awk -F" " '{print $3}')"
        [ -f "$GRUB_EFINB_DIR/$grub_eficfg_MAC" ] && rm -f $GRUB_EFINB_DIR/$grub_eficfg_MAC
        ;;
      *:*:*:*:*:*)
        # list by MAC
	# for an Ethernet (ARP type 1) with address 88:99:AA:BB:CC:DD it would search for the filename grub.cfg-drbl-88:99:aa:bb:cc:dd (lowercase)
	grub_eficfg="$(echo $ih | tr "[A-Z]" "[a-z]")"
	# append "grub.cfg-drbl-" in the beginning
	grub_eficfg="grub.cfg-drbl-$grub_eficfg"
	# We'd better to clean the IP-based setting file if it exists since maybe it's created by ocsmgrd when received the results from client in the previous save/restoration. Although grub.cfg-drbl-$MAC has higher priority than "grub.cfg-drbl-C0A80001" style file in grub_efi, this NOT a must if we can find it, but we remove it to avoid confusion.
        IP="$(grep -E ${ih} $OCS_TMP | awk -F" " '{print $2}')"
	grub_eficfg_MIP="grub.cfg-drbl-${IP}"
        [ -f "$GRUB_EFINB_DIR/$grub_eficfg_MIP" ] && rm -f $GRUB_EFINB_DIR/$grub_eficfg_MIP
        ;;
    esac
    echo -n "Generate the grub uEFI netboot config file for host $ih ... "
    cp -f $GRUB_EFINB_DIR/grub.cfg_skeleton $GRUB_EFINB_DIR/$grub_eficfg
    echo "done!"
  done
  [ -f "$OCS_TMP" ] && rm -f $OCS_TMP
} # end of set_specific_host_grub_efi_conf
#
check_entryid_in_grub_efi_cfg() {
  local ENTRY_ID="$1"
  local GRUB_CONF_TMP="$2"
  if [ -z "$ENTRY_ID" ]; then
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "You must specify the image name! Program terminated!!!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     exit 1
  fi
  if [ -n "$GRUB_CONF_TMP" -a ! -e "$GRUB_CONF_TMP" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF_TMP not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  if ! grep -Eiq "^[[:space:]]*menuentry[[:space:]]+.*--id $ENTRY_ID" $GRUB_CONF_TMP; then
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "Unable to find the menuentry ($ENTRY_ID) ID! Make sure the $ENTRY_ID is labeled in $GRUB_CONF_TMP! Program terminated!!!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     exit 1
  fi
} # end of check_entryid_in_grub_efi_cfg
#
sub_default_grub_efi_img() {
  local ENTRY_ID="$1"  # E.g. drbl-client, clonezilla-se-client
  local GRUB_CONF_TMP="$2"
  local ENTRY_LABEL="$3"
  local lines begin_line end_line
  if [ -n "$GRUB_CONF_TMP" -a ! -e "$GRUB_CONF_TMP" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF_TMP not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  check_entryid_in_grub_efi_cfg "$ENTRY_ID" $GRUB_CONF_TMP
  # Set default menu and update the menuentry 
  perl -pi -e "s|^set default=.*|set default=$ENTRY_ID|g" $GRUB_CONF_TMP

  lines="$(get_grub_efi_image_block "--id $ENTRY_ID" $GRUB_CONF_TMP)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"

  if [ -n "$ENTRY_LABEL" ]; then
    echo The MENUENTRY LABEL is \"$ENTRY_LABEL\"
    # menuentry "Clonezilla" --id clonezilla-se-client {
    # ->
    # menuentry "Clonezilla: multicast restore precise-x86-20150504 to disk sda " --id clonezilla-se-client {
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|^[[:space:]]*menuentry .*|menuentry \"$ENTRY_LABEL\" --id $ENTRY_ID \{|i}"
    perl -pi -e "$sub_menu_label_cmd" $GRUB_CONF_TMP
  fi
} # end of sub_default_grub_efi_img
#
add_opt_in_pxelinux_cfg_block() {
  # add something like: ocs_opt="--language 0  -g auto -p true restoredisk 2disks hda hdb" in pxelinux config file
  local prot_dq="\\\""  # protection double quotation for later use.
  while [ $# -gt 0 ]; do
    case "$1" in
      -n|--no-dq) shift; prot_dq="" ;;
      -*)     echo "${0}: ${1}: invalid option in function add_opt_in_pxelinux_cfg_block"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  local label="$1"
  local opt_name="$2" # can be ocs_opt (for NFSRoot-based Clonezilla client) or ocs_live_run (for Clonezilla-live-based client)
  local opt_content="$3"
  local tag_found
  [ -z "$label" ] && echo "No label in add_opt_in_pxelinux_cfg_block!" && exit 1
  [ -z "$opt_name" ] && echo "opt_name NOT specified in add_opt_in_pxelinux_cfg_block! Abort!" && exit 1
  [ -z "$opt_content" ] && echo "opt_content NOT specified in add_opt_in_pxelinux_cfg_block! Abort!" && exit 1
  # Make sure there is no white space in the end of opt_content, i.e. e.g.
  # "clonezilla -l en_US.UTF-8 -p reboot -k  " -> "clonezilla -l en_US.UTF-8 -p reboot -k"
  # Otherwise it might cause the boot parameters to be wrongly parsed, i.e. the boot parameters:
  # ocs_live_run="clonezilla -l en_US.UTF-8 -p reboot -k  " net.ifnames=0
  # is wrongly parsed by Linux kernel 4.1 so that net.ifnames=0 won't take effect.
  opt_content="$(LC_ALL=C echo "$opt_content" | sed -r -e "s/[[:space:]]*$//g")"
  lines="$(get_pxecfg_image_block $label $PXE_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$label\" found in $PXE_CONF, skip adding that."
    return 1
  fi
  tag_found="$(LC_ALL=C head -n $end_line $PXE_CONF | tail -n $(($end_line-$begin_line)) | grep -Eiw "^[[:space:]]*append[[:space:]]*.*[[:space:]]+$opt_name=.*([[:space:]]+|$)")"
  if [ -z "$tag_found" ]; then
    # append ocs_opt=... in the end of append kernel parameter.
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}|i}"
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
  else
    # overwrite existing ocs_opt=...
    # ocs_opt must be the last parameters in default append for pxelinux.
    # If tag if found, 3 cases: (1) with "" (e.g. ocs_daemonon="ssh", (2) without "" (e.g. ocs_daemonon=ssh)
    # (3) nothing (except space) after =, e.g. 'ocs_daemonon='
    if [ -n "$(echo $tag_found | grep -iE "$opt_name=\"[^\"]*\"")" ]; then
      # case 1, e.g. ocs_daemonon="ssh"
      sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]*.*)[[:space:]]+$opt_name=\"[^\"]*\"([[:space:]]+.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}\$2|i}"
    else
      if [ -n "$(echo $tag_found | grep -iE "$opt_name=[^[:space:]]+")" ]; then
        # case 2, e.g. ocs_daemonon=ssh
        sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]*.*)[[:space:]]+$opt_name=[^[:space:]]+([[:space:]]+.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}\$2|i}"
      else
        # case 3, e.g. 'ocs_daemonon=', normally this is for 'locales=' or 'keyboard-layouts='
        sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]*.*)[[:space:]]+$opt_name=[[:space:]]+(.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq} \$2|i}"
      fi
    fi
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
  fi
} # end of add_opt_in_pxelinux_cfg_block
#
remove_opt_in_pxelinux_cfg_block() {
  local label="$1"
  local opt_name="$2" # can be ocs_opt (for NFSRoot-based Clonezilla client) or ocs_live_run (for Clonezilla-live-based client)
  local tag_found
  [ -z "$label" ] && echo "No label in remove_opt_in_pxelinux_cfg_block!" && exit 1
  # remove something like ocs_opt=... from the append .... like this in pxelinux config:
  # append ... ocs_opt="--language 0  -g auto -p true restoredisk 2disks hda hdb"...
  lines="$(get_pxecfg_image_block $label $PXE_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$label\" found in $PXE_CONF, skip removing that."
    return 1
  fi
  # 2 types of boot parameters, 1st one is with "=" (e.g. ocs_opt=...), the 2nd one is without "=" (e.g. quiet). Here first we test if the one with "=" is found or not.
  tag_found="$(LC_ALL=C head -n $end_line $PXE_CONF | tail -n $(($end_line-$begin_line)) | grep -Eiw "^[[:space:]]*append[[:space:]]*.*[[:space:]]+$opt_name=.*([[:space:]]+|$)")"
  if [ -n "$tag_found" ]; then
    # 1st type, i.e. with "=". 3 types of them. 
    # (1) with ", e.g. ocs_live_run="ocs-live-general"
    # (2) without ", e.g. ocs_live_run=ocs-live-general
    # (3) without " and nothing after '=', e.g. 'ocs_live_run='

    # (1) with ", e.g. ocs_live_run="ocs-live-general"
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)[[:space:]]+$opt_name=\"[^\"]*\"([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
    # (2) without ", e.g. ocs_live_run=ocs-live-general
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)[[:space:]]+$opt_name=[^[:space:]]+([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
    # (3) without " and nothing after '=', e.g. 'ocs_live_run='
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)[[:space:]]+$opt_name=[[:space:]]+(.*)|\$1 \$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
  else
    # 2nd type, i.e. without "=", or nothing. Even if nothing, perl won't fail. Therefore just run it.
    sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*append[[:space:]]+.*)[[:space:]]+$opt_name([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
  fi
} # end of remove_opt_in_pxelinux_cfg_block()
#
override_opt_in_pxelinux_cfg_block() {
  # Function to override all the boot parameters. E.g.
  # kernel vmlinuz-pxe
  # append initrd=initrd-pxe.img devfs=nomount drblthincli=off quiet
  local update_mode
  update_mode="append"  # By default this function is used to update the line begin with "append"
  while [ $# -gt 0 ]; do
    case "$1" in
      -k|--kernel) shift; update_mode="kernel" ;;
      -*)     echo "${0}: ${1}: invalid option in function add_opt_in_pxelinux_cfg_block"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  local label="$1"
  local all_opts="$2" # all the boot parameters
  [ -z "$label" ] && echo "No label in override_opt_in_pxelinux_cfg_block!" && exit 1
  lines="$(get_pxecfg_image_block $label $PXE_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$label\" found in $PXE_CONF, skip overwriding that."
    return 1
  fi
  sub_menu_label_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*${update_mode}[[:space:]]+).*$|\$1$all_opts|i}"
  LC_ALL=C perl -pi -e "$sub_menu_label_cmd" $PXE_CONF
} # end of override_opt_in_pxelinux_cfg_block
#
get_status_grub_efi_cfg_block() {
  local ENTRY_ID="$1"
  local GRUB_CONF_TMP="$2"
  local lines begin_line end_line rc block_status
  [ -z "$ENTRY_ID" -o -z "$GRUB_CONF_TMP" ] && return 1
  if [ -n "$GRUB_CONF_TMP" -a ! -e "$GRUB_CONF_TMP" ]; then
    return 2
  fi
  lines="$(get_grub_efi_image_block "--id $ENTRY_ID" $GRUB_CONF_TMP)"
  begin_line=$(echo $lines | awk -F" " '{print $1}')
  end_line=$(echo $lines | awk -F" " '{print $2}')  # end_line is useless in this function. Just keep it for completion
  if [ -n "$(LC_ALL=C sed -n "${begin_line}p" $GRUB_CONF_TMP | grep -E "^#menuentry")" ]; then
  # Found something like:
  # #menuentry "Clonezilla" --id clonezilla-se-client {
  # so it's disabled.
    block_status="hide"
  else
    block_status="reveal"
  fi
  echo "$block_status"
} # end of get_status_grub_efi_cfg_block
#
add_opt_in_grub_efi_cfg_block() {
  # add something like: ocs_opt=\"--language 0  -g auto -p true restoredisk 2disks hda hdb\" in grub efi nb config file
  local prot_dq="\\\\\""  # protection double quotation for later use.
  local status_saved
  while [ $# -gt 0 ]; do
    case "$1" in
      -n|--no-dq) shift; prot_dq="" ;;
      -*)     echo "${0}: ${1}: invalid option in function add_opt_in_grub_efi_cfg_block"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  local entry_id="$1" # e.g. "clonezilla-se-client"
  local opt_name="$2" # can be ocs_opt (for NFSRoot-based Clonezilla client) or ocs_live_run (for Clonezilla-live-based client)
  local opt_content="$3"
  local tag_found
  local sub_menu_entry_cmd
  [ -z "$entry_id" ] && echo "No entry_id in add_opt_in_grub_efi_cfg_block!" && exit 1
  [ -z "$opt_name" ] && echo "opt_name NOT specified in add_opt_in_grub_efi_cfg_block! Abort!" && exit 1
  [ -z "$opt_content" ] && echo "opt_content NOT specified in add_opt_in_grub_efi_cfg_block! Abort!" && exit 1
  if [ -n "$GRUB_CONF" -a ! -e "$GRUB_CONF" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  # Before adding option, we have to enable it because with grub there is no
  # way to hide unless with use # to comment the whole menuentry.
  # Save the status first
  status_saved="$(get_status_grub_efi_cfg_block "$entry_id" $GRUB_CONF)"
  hide_reveal_grub_efi_ent "$entry_id" reveal $GRUB_CONF
  #
  lines="$(get_grub_efi_image_block "--id $entry_id" $GRUB_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$entry_id\" found in $GRUB_CONF, skip adding that."
    return 1
  fi
  tag_found="$(LC_ALL=C head -n $end_line $GRUB_CONF | tail -n $(($end_line-$begin_line)) | grep -Eiw "^[[:space:]]*$linux_cmd[[:space:]]*.*[[:space:]]+$opt_name=.*([[:space:]]+|$)")"
  if [ -z "$tag_found" ]; then
    # append ocs_opt=... in the end of linux kernel parameter.
    sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]+.*)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}|i}"
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
  else
    # overwrite existing ocs_opt=...
    # ocs_opt must be the last parameters in default append for grub efi nb.
    # If tag if found, 3 cases: (1) with "" (e.g. ocs_daemonon="ssh", (2) without "" (e.g. ocs_daemonon=ssh),
    # (3) nothing (except space) after =, e.g. 'ocs_daemonon='
    if [ -n "$(echo $tag_found | grep -iE "$opt_name=\\\\\"[^\"]*\\\\\"")" ]; then
      # case 1, e.g. ocs_daemonon="ssh"
      sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]*.*)[[:space:]]+$opt_name=\"[^\"]*\"([[:space:]]+.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}\$2|i}"
    else
      if [ -n "$(echo $tag_found | grep -iE "$opt_name=[^[:space:]]+")" ]; then
        # case 2, e.g. ocs_daemonon=ssh
        sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]*.*)[[:space:]]+$opt_name=[^[:space:]]+([[:space:]]+.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq}\$2|i}"
      else
        # case 3, e.g. 'ocs_daemonon=', normally this is for 'locales=' or 'keyboard-layouts='
        sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]*.*)[[:space:]]+$opt_name=[[:space:]]+(.*$)|\$1 $opt_name=${prot_dq}${opt_content}${prot_dq} \$2|i}"
      fi
    fi
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
  fi
  # Restore the status
  hide_reveal_grub_efi_ent "$entry_id" "$status_saved" $GRUB_CONF
} # end of add_opt_in_grub_efi_cfg_block
#
remove_opt_in_grub_efi_cfg_block() {
  local entry_id="$1" # e.g. "clonezilla-se-client"
  local opt_name="$2" # can be ocs_opt (for NFSRoot-based Clonezilla client) or ocs_live_run (for Clonezilla-live-based client)
  local tag_found
  local sub_menu_entry_cmd
  local status_saved
  [ -z "$entry_id" ] && echo "No entry_id in remove_opt_in_grub_efi_cfg_block!" && exit 1
  if [ -n "$GRUB_CONF" -a ! -e "$GRUB_CONF" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  # Before adding option, we have to enable it because with grub there is no
  # way to hide unless with use # to comment the whole menuentry.
  # Save the status first
  status_saved="$(get_status_grub_efi_cfg_block "$entry_id" $GRUB_CONF)"
  hide_reveal_grub_efi_ent "$entry_id" reveal $GRUB_CONF
  # remove something like ocs_opt=... from the append .... like this in pxelinux config:
  # append ... ocs_opt="--language 0  -g auto -p true restoredisk 2disks hda hdb"...
  lines="$(get_grub_efi_image_block "--id $entry_id" $GRUB_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$entry_id\" found in $GRUB_CONF, skip removing that."
    return 1
  fi
  # 2 types of boot parameters, 1st one is with "=" (e.g. ocs_opt=...), the 2nd one is without "=" (e.g. quiet). Here first we test if the one with "=" is found or not.
  tag_found="$(LC_ALL=C head -n $end_line $GRUB_CONF | tail -n $(($end_line-$begin_line)) | grep -Eiw "^[[:space:]]*$linux_cmd[[:space:]]*.*[[:space:]]+$opt_name=.*([[:space:]]+|$)")"
  if [ -n "$tag_found" ]; then
    # 1st type, i.e. with "=". 2 types of them. 
    # (1) with ", e.g. ocs_live_run="ocs-live-general"
    # (2) without ", e.g. ocs_live_run=ocs-live-general
    # (3) without " and nothing after '=', e.g. 'ocs_live_run='

    # (1) with ", e.g. ocs_live_run="ocs-live-general"
    sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]+.*)[[:space:]]+$opt_name=\\\\\"[^\"]*\\\\\"([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
    # (2) without ", e.g. ocs_live_run=ocs-live-general
    sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]+.*)[[:space:]]+$opt_name=[^[:space:]]+([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
    # (3) without " and nothing after '=', e.g. 'ocs_live_run='
    sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]+.*)[[:space:]]+$opt_name=[[:space:]]+(.*)|\$1 \$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
  else
    # 2nd type, i.e. without "=", or nothing. Even if nothing, perl won't fail. Therefore just run it.
    sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*\\\$linux_cmd[[:space:]]+.*)[[:space:]]+$opt_name([[:space:]]+.*)|\$1\$2|i}"
    LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
  fi
  # Restore the status
  hide_reveal_grub_efi_ent "$entry_id" "$status_saved" $GRUB_CONF
} # end of remove_opt_in_grub_efi_cfg_block
#
override_opt_in_grub_efi_cfg_block() {
  # Function to override all the boot parameters. A grub config block is like:
  # menuentry "Debian Testing-Unstable Linux (DRBL mode, mostly local resources)" --id drbl-client {
  # echo "Enter DRBL..."
  # echo "Loading Linux vmlinuz-pxe..."
  # linux vmlinuz-pxe boot=live union=overlay config components nomodeset quiet net.ifnames=0  nosplash username=drbl keyboard-layouts=us locales=en_US.UTF-8 drbl_live_noconfx ocs_daemonon="ssh" noeject netboot=nfs nfsroot=192.168.7.254:/tftpboot/node_root/clonezilla-live/ dcs_put_dticons="no"
  # echo "Loading initial ramdisk initrd-pxe.img..."
  # initrd initrd-pxe.img
  # }
  local update_mode kernel_f
  local sub_menu_entry_cmd
  local status_saved
  update_mode="linux"  # By default this function is used to update the line begin with "linux"
  while [ $# -gt 0 ]; do
    case "$1" in
      -i|--initrd) shift; update_mode="initrd" ;;
      -*)     echo "${0}: ${1}: invalid option in function override_opt_in_grub_efi_cfg_block"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  local entry_id="$1" # e.g. "clonezilla-se-client"
  local all_opts="$2" # all the boot parameters
  [ -z "$entry_id" ] && echo "No entry_id in override_opt_in_grub_efi_cfg_block!" && exit 1
  if [ -n "$GRUB_CONF" -a ! -e "$GRUB_CONF" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "File $GRUB_CONF not found. No support for uEFI network boot."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  # Before adding option, we have to enable it because with grub there is no
  # way to hide unless with use # to comment the whole menuentry.
  # Save the status first
  status_saved="$(get_status_grub_efi_cfg_block "$entry_id" $GRUB_CONF)"
  hide_reveal_grub_efi_ent "$entry_id" reveal $GRUB_CONF
  lines="$(get_grub_efi_image_block "--id $entry_id" $GRUB_CONF)"
  begin_line="$(echo $lines | awk -F" " '{print $1}')"
  end_line="$(echo $lines | awk -F" " '{print $2}')"
  if [ -z "$begin_line" -o -z "$end_line" ]; then
    echo "No \"$entry_id\" found in $GRUB_CONF, skip removing that."
    return 1
  fi
  sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*${update_mode}[[:space:]]+).*$|\$1$all_opts|i}"
  LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
  # Update the echo command for kernel and initrd, too
  case "$update_mode" in
   linux)
     # When in this mode, the 1st parameter in linux "line" is kernel, e.g.
     # linux vmlinuz-pxe root=... ro quiet...
     kernel_f="$(echo $all_opts | awk -F" " '{print $1}')"
     sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*)echo \"Loading Linux kernel.*\"$|\$1echo \"Loading Linux kernel $kernel_f\"|i}"
     LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
     ;;
   initrd)
     sub_menu_entry_cmd="if ($begin_line..$end_line) {s|(^[[:space:]]*)echo \"Loading initial ramdisk.*\"$|\$1echo \"Loading initial ramdisk $all_opts\"|i}"
     LC_ALL=C perl -pi -e "$sub_menu_entry_cmd" $GRUB_CONF
     ;;
  esac
  # Restore the status
  hide_reveal_grub_efi_ent "$entry_id" "$status_saved" $GRUB_CONF
} # end of override_opt_in_grub_efi_cfg_block
#
confirm_continue_or_not_default_quit() {
  local ans_continue
  local job_before_quit job_des
  while [ $# -gt 0 ]; do
    case "$1" in
      -d|--description)
         shift
         if [ -z "$(echo $1 |grep ^-.)" ]; then
           # skip the -xx option, in case 
           job_des="$1"
           shift
         fi
         if [ -z "$job_des" ]; then
           echo "-d is used, but no job_des assigned."
           echo "$msg_program_stop"
           [ "$save_restore_error_log" = "yes" ] && copy_error_log
           exit 1
         fi
         ;;
      -*)     echo "${0}: ${1}: invalid option"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  job_before_quit="$1"
  if [ -n "$job_des" ]; then
    echo "$job_des"
  fi
  echo "$msg_are_u_sure_u_want_to_continue"
  echo -n "[y/N] "
  read ans_continue
  case "$ans_continue" in
       y|Y|[yY][eE][sS])
          echo "$msg_ok_let_do_it!"
          ;;
       *)
          echo "$msg_program_stop!"
          [ -n "$job_before_quit" ] && $job_before_quit
	  my_ocs_exit 1
          ;;
  esac
} # end of confirm_continue_or_not_default_quit
#
confirm_continue_or_not_default_continue() {
  local ans_continue
  local job_before_quit job_des
  while [ $# -gt 0 ]; do
    case "$1" in
      -d|--description)
         shift
         if [ -z "$(echo $1 |grep ^-.)" ]; then
           # skip the -xx option, in case 
           job_des="$1"
           shift
         fi
         if [ -z "$job_des" ]; then
           echo "-d is used, but no job_des assigned."
           echo "$msg_program_stop"
           [ "$save_restore_error_log" = "yes" ] && copy_error_log
           exit 1
         fi
         ;;
      -*)     echo "${0}: ${1}: invalid option"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  job_before_quit="$1"
  if [ -n "$job_des" ]; then
    echo "$job_des"
  fi
  echo "$msg_are_u_sure_u_want_to_continue"
  echo -n "[Y/n] "
  read ans_continue
  case "$ans_continue" in
       n|N|[nN][oO])
          echo "$msg_program_stop!"
          [ -n "$job_before_quit" ] && $job_before_quit
	  my_ocs_exit 1
          ;;
       *)
          echo "$msg_ok_let_do_it!"
	  ;;
  esac
} # end of confirm_continue_or_not_default_continue
#
confirm_continue_no_default_answer() {
  local ans_ ans_continue continue_choice
  local job_before_quit job_des
  continue_choice=""
  while [ $# -gt 0 ]; do
    case "$1" in
      -d|--description)
         shift
         if [ -z "$(echo $1 |grep ^-.)" ]; then
           # skip the -xx option, in case 
           job_des="$1"
           shift
         fi
         if [ -z "$job_des" ]; then
           echo "-d is used, but no job_des assigned."
           echo "$msg_program_stop"
           [ "$save_restore_error_log" = "yes" ] && copy_error_log
           exit 1
         fi
         ;;
      -*)     echo "${0}: ${1}: invalid option"
              echo "$msg_program_stop"
              [ "$save_restore_error_log" = "yes" ] && copy_error_log
              exit 2 ;;
      *)      break ;;
    esac
  done
  job_before_quit="$1"
  while [ -z "$continue_choice" ]; do
   if [ "$ocs_prompt_mode" = "tui" ]; then
     # Because dialog/whiptail "--yesno" must have a yes or no, we choose no here.
     $DIA --backtitle "$msg_nchc_free_software_labs" --title "$msg_nchc_clonezilla" \
     --defaultno --yesno "${job_des}${msg_are_u_sure_u_want_to_continue}" 0 0 
     ans_="$?"
     # Convert ans_ to ans_continue
     case "$ans_" in
       0) # yes is chosen
          ans_continue="yes";;
       1) # no is chosen
          ans_continue="no";;
     esac
   else
     if [ -n "$job_des" ]; then
       echo "$job_des"
     fi
     echo -n "$msg_are_u_sure_u_want_to_continue (y/n) "
     read ans_continue
   fi
   case "$ans_continue" in
        y|Y|[yY][eE][sS])
           continue_choice="yes"
           echo "$msg_ok_let_do_it!"
           ;;
        n|N|[nN][oO])
           continue_choice="no"
           echo "$msg_program_stop!"
           [ -n "$job_before_quit" ] && $job_before_quit
	   my_ocs_exit 1
           ;;
        *)
           [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
           echo "$msg_you_have_to_enter_yes_or_no!"
           [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
           echo $msg_delimiter_star_line
           ;;
   esac
  done
} # end of confirm_continue_no_default_answer
#
filter_cl_gp_boot_param(){
  # Function to filter the boot parameters which should not be used in PXE RAM based drbl/clonezilla/gparted client.
  # Used for programs drbl-sl and drbl-live
  # (1) For /proc/cmdline, it's like (customized by user):
  # BOOT_IMAGE=/live/vmlinuz initrd=/live/initrd.img boot=live union=overlay username=user config components nomodeset quiet vga=785 ip= net.ifnames=0  nosplash i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1 keyboard-layouts=NONE locales=en_US.UTF-8 drbl_live_noconfx ocs_daemonon="ssh" ocs_prerun1="ifconfig eth0 192.168.120.3; route add default gw 192.168.120.254 eth0; ifconfig eth1 192.168.7.254 netmask 255.255.255.0; echo nameserver 8.8.8.8 > /etc/resolv.conf" ocs_prerun2="mount -t nfs 192.168.120.254:/home/partimag /home/partimag" ocs_prerun3="drbl-live --batch --skip-pause-in-the-end --no-prompt-drbl-live start" ocs_prerun5="perl -pi -e 's/timeout 70/timeout 10/' /tftpboot/nbi_img/pxelinux.cfg/default"
  # (2) For isolinux.cfg or syslinux.cfg, it's like (customized by user):
  # append initrd=/live/initrd.img boot=live union=overlay username=user config components nomodeset quiet vga=785 ip= net.ifnames=0  nosplash i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1 keyboard-layouts=NONE locales=en_US.UTF-8 drbl_live_noconfx ocs_daemonon="ssh" ocs_prerun1="ifconfig eth0 192.168.120.3; route add default gw 192.168.120.254 eth0; ifconfig eth1 192.168.7.254 netmask 255.255.255.0; echo nameserver 8.8.8.8 > /etc/resolv.conf" ocs_prerun2="mount -t nfs 192.168.120.254:/home/partimag /home/partimag" ocs_prerun3="drbl-live --batch --skip-pause-in-the-end --no-prompt-drbl-live start" ocs_prerun5="perl -pi -e 's/timeout 70/timeout 10/' /tftpboot/nbi_img/pxelinux.cfg/default" 
  # (3) For grub.cfg, it's like:
  # $linux_cmd /live/vmlinuz boot=live union=overlay username=user config components quiet noswap edd=on nomodeset enforcing=0 locales= keyboard-layouts= ocs_live_run="ocs-live-general" ocs_live_extra_param="" ocs_live_batch="no" vga=788 ip= net.ifnames=0  splash i915.blacklist=yes radeonhd.blacklist=yes nouveau.blacklist=yes vmwgfx.enable_fbdev=1
  # So the 1st two items should be removed
  awk -F" " '{for (i=3; i<=NF; ++i) print $i}' | xargs echo |\
  sed -r -e "s|append||g" |\
  sed -r -e "s|BOOT_IMAGE=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|initrd=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|vga=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|ip=[^[:space:]]*[[:space:]]?||g" | \
  sed -r -e "s|keyboard-layouts=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|locales=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|[^[:space:]]+.blacklist=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|vmwgfx.enable_fbdev=[^[:space:]]+[[:space:]]?||g" | \
  sed -r -e "s|ocs_prerun[[:digit:]]*=\".*\"||g" | \
  sed -r -e "s|ocs_daemon.*=\".*\"||g" | \
  sed -r -e "s|drbl_live_noconfx||g" | \
  sed -r -e "s|toram=?[^[:space:]]*[[:space:]]?||g" | \
  sed -r -e "s|^[[:space:]]*||g" | \
  sed -r -e "s|[[:space:]]+$||g"
} # end of filter_cl_gp_boot_param
#
is_valid_IPv4_add() {
  local input_ip="$1"
  local rc=1
  if [ -n "$(echo $input_ip | grep -Eo "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")" ]; then
    rc=0
  else
    rc=1
  fi
  return $rc
} # end of is_valid_IPv4_add
#
deploy_pxecfg_grubefi_files(){
  # This function will set the specific config or just keep the "default"
  if [ "$LIST_HOST" = "on" ]; then
    # specify the nodes if assigned by user
    echo "Create specific config for PXE and GRUB EFI NB client."
    set_specific_host_pxe_conf `cat $HOSTS_TMP`
    set_specific_host_grub_efi_conf `cat $HOSTS_TMP`
  else
    # for all clients, so we just keep the file pxelinux.cfg/default, no others.
    echo "This is for all clients, so we remove other host-based PXE config files in $PXELINUX_DIR/ and keep $PXE_CONF."
    clean_stale_node_pxe_cfg
    clean_stale_node_grub_efi_cfg
  fi
} # end of deploy_pxecfg_grubefi_files
#
gen_dnsmasq_cfg() {
  local srv_cfg="$1"
  local gen_mode="proxy"  # default mode is proxy
  local dnsmasq_v pxelinux_fn
  local allow_1_nic="no" # By default should be in DRBL mode, i.e., 2 or more NICs.
  if [ -z "$srv_cfg" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "No config file assigned in function gen_dnsmasq_cfg!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo "$msg_program_stop"
    exit 1
  fi
  while [ $# -gt 0 ]; do
    case "$1" in
      -a|--allow-1-nic) allow_1_nic="yes"; shift;;
      -r|--range)
          shift; gen_mode="range"
          if [ -z "$(echo $1 |grep ^-.)" ]; then
            # skip the -xx option, in case 
            dhcp_range="$1"
            shift
          fi
          [ -z "$dhcp_range" ] && echo "-m is used, but no dhcp_range was assigned." && exit 1
          shift
          ;;
      -*) echo "${0}: ${1}: invalid option in gen_dnsmasq_cfg." | tee -a ${OCS_LOGFILE} >&2
          echo "$msg_program_stop" | tee -a ${OCS_LOGFILE}
          [ "$save_restore_error_log" = "yes" ] && copy_error_log
          exit 2 ;;
      *)  break ;;
    esac
  done
  # Generate dnsmasq.conf
  cat <<-DNSMQSQ_END > $dnsmasq_cfg
# Configured by DRBL/Clonezilla
bind-interfaces
log-dhcp
dhcp-no-override
enable-tftp
tftp-root=$pxecfg_pd
DNSMQSQ_END

  case "$gen_mode" in
    proxy) all_eth_dev="$(LC_ALL=C get-all-nic-ip -d)"
           uplink_eth="$(LC_ALL=C get-all-nic-ip -u)"
           for inet in $all_eth_dev; do
             if [ "$allow_1_nic" = "no" ]; then
               # Do not allow 1 NIC, so skip if uplink is the same with all NIC.
               [ "$inet" = "$uplink_eth" ] && continue
             fi
             ip="$(LC_ALL=C drbl-get-ipadd $inet)"
             echo "dhcp-range=$ip,proxy" >> $dnsmasq_cfg
           done
           ;;
    range) echo "dhcp-range=$dhcp_range" >> $dnsmasq_cfg;;
        *) echo "${0}: ${1}: Unknown gen_mode in gen_dnsmasq_cfg." | tee -a ${OCS_LOGFILE} >&2
           echo "$msg_program_stop" | tee -a ${OCS_LOGFILE}
           [ "$save_restore_error_log" = "yes" ] && copy_error_log
           exit 2 ;;
  esac

  # Older dnsmasq (<2.75) will automatically append ".0" to pxelinux
  dnsmasq_v="$(query_pkg_ver dnsmasq)"
  if [ -z "$dnsmasq_v" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Package dnsmasq is not installed. Skip generating dnsmasq.conf."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 1
  fi
  # dnsmasq version >= 2.76 will not append ".0" to basename.
  # Ref: http://www.thekelleys.org.uk/dnsmasq/CHANGELOG (search basename)
  if [ "$dnsmasq_v" \> "2.75" -o "$dnsmasq_v" = "2.76" ]; then
    pxelinux_fn="pxelinux.0"
  else
    pxelinux_fn="pxelinux"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Warning!"
    echo "Package dnsmasq is too old. It's recommended to use version >= 2.75."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
  
  # pxe-service mode does not work for non-proxy mode. It fails for supporting uEFI secure netboot
  # Hence we use dhcp-boot for non-proxy mode. This is a workaround to support uEFI secure netboot.
  # Ref: http://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2018q3/012476.html
  case "$gen_mode" in
    proxy) 
     cat <<-DNSMQSQ_END >> $dnsmasq_cfg 

## PXEClient:Arch:00000
pxe-service=X86PC, "Boot BIOS PXE", $pxelinux_fn

## PXEClient:Arch:00007
pxe-service=BC_EFI, "Boot UEFI BC", bootx64.efi

## PXEClient:Arch:00009
pxe-service=X86-64_EFI, "Boot UEFI X86-64", bootx64.efi

pxe-prompt="Booting DRBL/Clonezilla Client", 1
DNSMQSQ_END
     ;;
    range) 
     cat <<-DNSMQSQ_END >> $dnsmasq_cfg 

dhcp-boot=$pxelinux_fn
dhcp-match=set:efi-x86_64,option:client-arch,7
dhcp-boot=tag:efi-x86_64,bootx64.efi
DNSMQSQ_END
     ;;
   esac
} # end of gen_dnsmasq_cfg
#
query_pkg_ver() {
  local pkg_ rc
  pkg_="$1"
  if [ -z $"pkg_" ]; then
    return 1
  fi
  if [ -e /etc/debian_version ]; then
    # Debian, Ubuntu
    ver_="$(LC_ALL=C dpkg-query -W -f='${Version}\n' ${pkg_} 2>/dev/null)"
    rc=$?
  else
    # Fedora, CentOS, RHEL, SuSE...
    ver_="$(LC_ALL=C rpm -q --qf "%{VERSION}\n" ${pkg_} 2>/dev/null)"
    rc=$?
  fi
  if [ "$rc" -eq 0 ]; then
    echo "$ver_"
  fi
  return $rc
} # end of query_pkg_ver
#
function check_url(){
  # Function to check if URL exists or not.
  # Ref: https://gist.github.com/hrwgc/7455343
  local url_t="$1"
  local rc
  if [ -n "$(LC_ALL=C wget --spider -S $url_t 2>&1 | grep -E 'HTTP/1.1 200 OK')" ]; then
    rc=0
  else
    rc=1
  fi
  return $rc
} # end of check_url
#
get_smtd_smmcb_switch() {
  # Function to assign the on/off switch for -smtd/-smmcb
  # For x86-64: off, others: on
  local running_cpu
  # smtd_smmcb_switch is a global variable
  running_cpu="$(uname -m)"
  case "$running_cpu" in
    x86_64) smtd_smmcb_switch="off";;
         *) smtd_smmcb_switch="on";;
  esac
} # end of get_smtd_smmcb_switch