File: drblpush

package info (click to toggle)
drbl 5.7.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,984 kB
  • sloc: sh: 43,522; perl: 8,820; xml: 867; makefile: 131
file content (5108 lines) | stat: -rwxr-xr-x 231,759 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
#!/usr/bin/perl -X
#
# Copyright (C) 2002-2012 by NCHC, Steven Shiau, K. L. Huang, and Ceasar Sun
# (steven _at nchc org tw, klhaung _at_ gmail com, ceasar _at_ nchc org tw)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Version 0.1, by K. L. Huang, klhaung _at_ gmail com, especially for Debian
# Modified by Steven Shiau, steven _at_ clonezilla org DRBL for Redhat

# setting
# timed login to GDM default time (seconds)
our $TIMED_GDM_TIME_DEFAULT="30";

# Swap size for client to open
our $MAXSWAPSIZE_DEFAULT="128";

# default autologin or timed login account password length
our $ACCOUNT_PASSWD_LENGTH_DEFAULT="8";

# default client no connected to some ethernet port
our $DEFAULT_CLIENT_NO_EACH_PORT="12";
# $assign_client_no_each_port is assign by -p or --port_client_no
our $assign_client_no_each_port;

# default boot prompt timeout for PXE client
our $DEFAULT_CLIENT_SYSTEM_BOOT_TIMEOUT="70";

#
our $DEFAULT_NISDOMAINNAME="penguinzilla";
our $DEFAULT_DOMAINNAME="drbl.org";

# flag to turn on/off NAT service in drbl server
our $drbl_server_as_NAT_server;

# This parameters are defined in drbl.conf or environment variables (e.g. DRBL_SCRIPT_PATH).
our $DRBL_SCRIPT_PATH;
our $drbl_setup_path;
our $drbl_syscfg;
# file name to record the auto login ID and passwd
our $AUTO_LOGIN_ID_PASSWD;
# file to record the IP and hostname for clients
our $IP_HOST_TABLE;
our $CLIENT_IP_HOSTNAME_LIST;
our $drblroot;
our $drbl_common_root;
our $query_pkglist_cmd;
our $DHCPD_DEFAULT_LEASE_TIME;
our $DHCPD_MAX_LEASE_TIME;
our $pxecfg_pd;

# First we need to get DRBL_SCRIPT_PATH.
chomp($DRBL_SCRIPT_PATH=`LC_ALL=C get-drbl-conf-param DRBL_SCRIPT_PATH`);
$ENV{'PATH'} = "$ENV{'PATH'}:$DRBL_SCRIPT_PATH/sbin:$DRBL_SCRIPT_PATH/bin:";

# Get them from drbl.conf
chomp($drbl_setup_path=`LC_ALL=C get-drbl-conf-param drbl_setup_path`);
chomp($drbl_syscfg=`LC_ALL=C get-drbl-conf-param drbl_syscfg`);
chomp($AUTO_LOGIN_ID_PASSWD=`LC_ALL=C get-drbl-conf-param AUTO_LOGIN_ID_PASSWD`);
# We use $CLIENT_IP_HOSTNAME_LIST (IP_HOST_TABLE) as the temp file in drblpush working dir.
chomp($IP_HOST_TABLE=`LC_ALL=C get-drbl-conf-param IP_HOST_TABLE`);
chomp($CLIENT_IP_HOSTNAME_LIST=`LC_ALL=C basename $IP_HOST_TABLE`);
chomp($drblroot=`LC_ALL=C get-drbl-conf-param drblroot`);
chomp($drbl_common_root=`LC_ALL=C get-drbl-conf-param drbl_common_root`);
chomp($query_pkglist_cmd=`LC_ALL=C get-drbl-conf-param query_pkglist_cmd`);
chomp($DHCPD_DEFAULT_LEASE_TIME=`LC_ALL=C get-drbl-conf-param DHCPD_DEFAULT_LEASE_TIME`);
chomp($DHCPD_MAX_LEASE_TIME=`LC_ALL=C get-drbl-conf-param DHCPD_MAX_LEASE_TIME`);
chomp($pxecfg_pd=`LC_ALL=C get-drbl-conf-param pxecfg_pd`);
chomp($ocs_img_repo_dir_default=`LC_ALL=C get-drbl-conf-param ocsroot`);

# the created config filename
our $DRBLPUSH_CONF="drblpush.conf";
# file to record the hosts
our $hosts_list="hosts_list.drbl";
# file to record the public IP for clients
our $public_ip_list="public_ip.drbl";
our @ip_sys_prefix;
our @ip_sys;
our $public_ip_port;
our $public_ip_addr;
# $pub_port_NAT is when there is no public IP in this drbl server, one of those
# private IPs which is connected to NAT server.
our $pub_port_NAT;

our $purge_client;
our $keep_client;
our $client_startup_mode;
# DRBL SSI (Single System Image) MODE: clients use the tarball template in $drbl_common_root/drbl_ssi for etc, var. There is a program "drbl-ssi-client-prepare" will be run in init.drbl to modify the necessary config of etc when client boots.
# Clonezilla box mode = DRBL SSI mode + runlevel 1 in client
our $drbl_mode;
our $drbl_ssi_mode;
our $clonezilla_mode;
our $clonezilla_box_mode;
our $run_drbl_ocs_live_prep="yes";
our $drbl_ocs_live_server;
our $live_client_cpu_mode;
our $ocs_img_repo_dir;
our $ocs_img_repo_dir_default;
# switch for local swap in client
our $swap_create;
our $client_exist_flag;
# default color for warning and error
#our $color_warn="yellow";
our $color_warn="Bold Yellow";
our $color_fail="red";
our $add_start_drbl_services_after_cfg="yes";
our $continue_with_one_port;

# use some perl modules
use Term::ANSIColor;
use File::Path;
# Import locale-handling tool set from POSIX module.
use POSIX qw(locale_h);
# set the locale to C
setlocale(LC_ALL, "C");

#
# ------------------------------------------------------------------------
# Begin of the program
# subroutines
require "$DRBL_SCRIPT_PATH/sbin/drbl-perl-functions";

chomp($orig_wd=`LC_ALL=C pwd`);
chomp($drblpush_wd=`LC_ALL=C mktemp -d /tmp/drblpush_wd.tmp.XXXXXX`);
# before changing to working directory, we copy the macadr-* into working dir
system("cp -f macadr-*.txt $drblpush_wd > /dev/null 2>&1");
chdir ($drblpush_wd) || die ("Could not change to new working directory!!!");

sub set_client_public_ip {
  # $_[0]: file to input containing client IPs (input)
  # $_[1]: file to output containing client public IPs parameters (return)
  my @drbl_ip=`cat $_[0]`;
  my $public_ip_file="$_[1]";

  my $saved_ip="";
  my $saved_gw="";
  my $saved_netmask="255.255.255.0";
  my $public_ip;
  my $public_gw;
  my $public_netmask;
  my @public_network_param;
  my $first_saved_ip;

sub check_net_digit {
    my $check_ip="$_[0]";
    my $check_type="$_[1]"; # 2 values: IP or NETMASK
    my @check_ip_each=split(/\./,$check_ip);
    if (@check_ip_each != "4") { return "failed"; }
    if ($check_type eq "IP") {
      # check the first and last digit, it can not be 255 or 0.
      if ($check_ip_each[$#$check_ip_each] eq "0" || $check_ip_each[$#$check_ip_each] eq "255" ) {
         print "$check_ip_each[$#$check_ip_each] $lang_deploy{\"can_not_be_the_last_IP\"}!!!\n";
         return "failed";
      }
      if ($check_ip_each[0] eq "0" || $check_ip_each[0] eq "255" ) {
         print "$check_ip_each[0] $lang_deploy{\"can_not_be_the_first_IP\"}!!!\n";
         return "failed";
      }
    }

    foreach $DIG (@check_ip_each) {
      if ($check_type eq "IP") {
        if ($DIG > "255" || $DIG < "0") {
          return "failed";
        }
      }elsif ($check_type eq "NETMASK"){
        if ($DIG >= "256") {
          return "failed";
        }
      }
    }
} # end of sub check_net_digit

sub get_network_param {
    $IP="$_[0]";
    $saved_ip="$_[1]";
    $saved_gw="$_[2]";
    $saved_netmask="$_[3]";
    print "$lang_deploy{\"enter_public_IP_for_the_client\"} ($lang_deploy{\"its_IP_in_DRBL_is\"} $IP)\n[$saved_ip] ";
    chomp($public_ip=<STDIN>);
    if ($public_ip eq ""){
      $public_ip=$saved_ip;
    }
    my $chk_rlt=check_net_digit($public_ip,"IP");
    while ($chk_rlt eq "failed") {
       print "$lang_deploy{\"wrong_entered_IP\"}\n";
       chomp($public_ip=<STDIN>);
       $chk_rlt=check_net_digit($public_ip,"IP");
    }
    print "public_ip $public_ip\n" if $verbosity >=2;

    @networkIp=split(/\./,$public_ip);
    my $IP_PREFIX=$networkIp[0].".".$networkIp[1].".".$networkIp[2];
    $saved_ip=$IP_PREFIX.".".++$networkIp[3];
    print "network $IP_PREFIX.0\n" if $verbosity >=2;
    print "saved_ip $saved_ip\n" if $verbosity >=2;
    $saved_gw=$IP_PREFIX.".".254;

    # public ip gateway
    print "$lang_deploy{\"enter_gateway_for_client\"} ($lang_deploy{\"its_IP_in_DRBL_is\"} $IP) \n[$saved_gw] ";
    chomp($public_gw=<STDIN>);
    if ($public_gw eq "") { $public_gw=$saved_gw; }
    my $chk_rlt=check_net_digit($public_gw,"IP");
    while ($chk_rlt eq "failed") {
       print "$lang_deploy{\"wrong_entered_IP\"}\n";
       chomp($public_gw=<STDIN>);
       $chk_rlt=check_net_digit($public_gw,"IP");
    }
    $saved_gw=$public_gw;
    print "public_gw is $public_gw\n" if $verbosity >=2;
    print "saved_gw is $saved_gw\n" if $verbosity >=2;


    # public ip netmask
    print "$lang_deploy{\"enter_netmask_for_client\"} ($lang_deploy{\"its_IP_in_DRBL_is\"} $IP) \n[$saved_netmask] ";
    chomp($public_netmask=<STDIN>);
    if ($public_netmask eq "") { $public_netmask="$saved_netmask" }
    my $chk_rlt=check_net_digit($public_netmask,"NETMASK");
    while ($chk_rlt eq "failed") {
       print "$lang_deploy{\"wrong_entered_netmask\"}\n";
       chomp($public_netmask=<STDIN>);
       $chk_rlt=check_net_digit($public_netmask,"NETMASK");
    }
    $saved_netmask=$public_netmask;
    print "public_netmask is $public_netmask\n" if $verbosity >=2;
    print "saved_netmask is $saved_netmask\n" if $verbosity >=2;

    return $saved_ip, $saved_gw, $saved_netmask, $public_ip, $public_gw, $public_netmask;
} # end of sub get_network_param

  chomp($public_ip_tmp=`LC_ALL=C mktemp /tmp/public_ip_tmp.XXXXXX`);
  chomp($public_ip_guess=`LC_ALL=C mktemp /tmp/public_ip_guess.XXXXXX`);
  open(PUBLIC_IP_FILE,">$public_ip_tmp") or die "$lang_deploy{\"failed_to_open_file\"}  \"$public_ip_tmp\"\n";
  open(PUBLIC_IP_GUESS_FILE,">$public_ip_guess") or die "$lang_deploy{\"failed_to_open_file\"}  \"$public_ip_guess\"\n";
  print "Clients' IPs: @drbl_ip\n" if $verbosity >=2;

# prepare the public ip file, one for guessed from first input, the other for
# entering one by one.
  print PUBLIC_IP_FILE <<END_PUBLIC_IP;
# The private IP is for the client connected to DRBL server.
# The public IP is for the client connected to WAN.
#------------------------------------------------------------
#private IP \t public IP \t netmask \t gateway
END_PUBLIC_IP

  print PUBLIC_IP_GUESS_FILE <<END_PUBLIC_IP_GUESS;
# The private IP is for the client connected to DRBL server.
# The public IP is for the client connected to WAN.
#------------------------------------------------------------
#private IP \t public IP \t netmask \t gateway
END_PUBLIC_IP_GUESS

  chomp($IP=@drbl_ip[0]);
  # get first public ip for client
  get_network_param($IP, $saved_ip, $saved_gw, $saved_netmask);
  $first_saved_ip=$saved_ip;

  print PUBLIC_IP_FILE <<END_PUBLIC_IP;
$IP \t $public_ip \t $public_netmask \t $public_gw
END_PUBLIC_IP

  print PUBLIC_IP_GUESS_FILE <<END_PUBLIC_IP_GUESS;
$IP \t $public_ip \t $public_netmask \t $public_gw
END_PUBLIC_IP_GUESS

  foreach $IP (@drbl_ip[1..$#drbl_ip]) {
    chomp($IP);
    $public_ip=$saved_ip;
    @networkIp=split(/\./,$public_ip);
    my $IP_PREFIX=$networkIp[0].".".$networkIp[1].".".$networkIp[2];
    $saved_ip=$IP_PREFIX.".".++$networkIp[3];

    $public_netmask=$saved_netmask;
    $public_gw=$saved_gw;
    print PUBLIC_IP_GUESS_FILE <<END_PUBLIC_IP_GUESS;
$IP \t $public_ip \t $public_netmask \t $public_gw
END_PUBLIC_IP_GUESS
  }

  print "#$delimiter{\"dash_line\"}\n";
  print "$lang_deploy{\"set_client_public_IP_as\"}\n";
  print "#$delimiter{\"dash_line\"}\n";
  system("LC_ALL=C cat $public_ip_guess");
  print "#$delimiter{\"dash_line\"}\n";
  print "$lang_text{\"Accept\"} ? [Y/n] ";
  chomp($value=<STDIN>);
  SWITCH: for ($value) {
	  /^n$|^no$/i && do {
            # Enter each one by one
            foreach $IP (@drbl_ip[1..$#drbl_ip]) {
              chomp($IP);
              # use the first one saved for initial prompt value to user
              $saved_ip=$first_saved_ip;
              get_network_param($IP, $saved_ip, $saved_gw, $saved_netmask);
              print PUBLIC_IP_FILE <<END_PUBLIC_IP;
$IP \t $public_ip \t $public_netmask \t $public_gw
END_PUBLIC_IP
            }
            close(PUBLIC_IP_FILE);
            # put the result file to working directory
            system("LC_ALL=C cp -f $public_ip_tmp $public_ip_file");
            last SWITCH;
	  };
	  /.*/ && do {
            # accept the guess one, output the result
            close(PUBLIC_IP_GUESS_FILE);
            # put the result file to working directory
            system("LC_ALL=C cp -f $public_ip_guess $public_ip_file");
            last SWITCH;
	  };
  }

  unlink ($public_ip_tmp) if -f $public_ip_tmp;
  unlink ($public_ip_guess) if -f $public_ip_guess;
} # end of sub set_client_public_ip
#
sub set_autologin_passwd{
  print "$lang_deploy{\"use_random_password\"}\n".
        "[Y/n] ";
  chomp($auto_login_random_passwd=<STDIN>);
  if ($auto_login_random_passwd eq "n" || $auto_login_random_passwd eq "N" || $auto_login_random_passwd eq "no" || $auto_login_random_passwd eq "NO") {
      # input password for client auto-login account
      print "$lang_deploy{\"enter_password_for_autologin_accounts\"}\n";
      # we set 2 different passwords to make while loop works.
      $client_autologin_passwd1="init1";
      $client_autologin_passwd2="init2";
      while ($client_autologin_passwd1 ne $client_autologin_passwd2 || ($client_autologin_passwd1 eq "" && $client_autologin_passwd2 eq "" )) {
           print "$lang_deploy{\"whats_client_autologin_passwd\"}\n";
  	 # turn off echo
           system "LC_ALL=C stty -echo";
           chomp($client_autologin_passwd1=<STDIN>);
  	 # turn on echo
           system "LC_ALL=C stty echo";
           print "$lang_deploy{\"retype_autologin_passwd\"}\n";
           system "LC_ALL=C stty -echo";
           chomp($client_autologin_passwd2=<STDIN>);
           system "LC_ALL=C stty echo";
        if ($client_autologin_passwd1 ne $client_autologin_passwd2) {
  	  print colored ("$lang_deploy{\"sorry_passwd_not_match\"}\n", "$color_warn");
        }elsif ($client_autologin_passwd1 eq "" && $client_autologin_passwd2 eq "" ){
  	  print colored ("$lang_deploy{\"sorry_passwd_can_not_empty\"}\n", "$color_warn");
        }
      }
      $client_autologin_passwd=$client_autologin_passwd1;
  }else{
      # Random password for client auto-login account
      $client_autologin_passwd="$ACCOUNT_PASSWD_LENGTH_DEFAULT";
      print "$lang_deploy{\"ok_let_continue\"}\n";
  }
} # end of set_autologin_passwd

#
sub interactive_mode {
        my $dnsdomain_sys, $nisdomain_sys, $hostname_sys;
	#we will scan the ethernet from $ethernet_list[0]...
	#use public IP in alias interface, private IP in real interface,
	#Ex: eth0: 192.168.0.254, eth0:1 61.216.116.23

	my $ethernet_list_;
	print "Finding the available ethernet ports...\n" if $verbosity >=2;
	chomp($ethernet_list_=`get-all-nic-ip -d`);
	my @ethernet_list=split(/ /,$ethernet_list_);
	my @ethernet_sys; # the private ethernet we found and useful, ex:"eth1"
	my @range_start;
	my @range_end;
	my @MAC_file;
	my $one_ethernet_port_server="no";
	my $use_proxy_dhcp="no";
	my $DHCPOFFER_siaddr="";
	my $DHCPOFFER_yiaddr="";
	my $DHCPOFFER_prefix="";
	my $DHCPOFFER_eth="";

        # Try to get setting from system
        chomp($dnsdomain_sys=`dnsdomainname`);
        chomp($nisdomain_sys=`nisdomainname`);
	chomp($hostname_sys=`hostname`);
        my @client_hostname_prefix_default=split(/\./,$hostname_sys);
	# Append "-" so that the hostname for client is like: prefix-192-168-1-1
	$client_hostname_prefix_default[0]="$client_hostname_prefix_default[0]"."-";
        print "DNSDOMAIN in system is $dnsdomain_sys\n" if $verbosity >= 2;
        print "NISDOMAIN in system is $nisdomain_sys\n" if $verbosity >= 2;
        print "Client hostname prefix default is $client_hostname_prefix_default[0]\n" if $verbosity >= 2;

        unlink ($DRBLPUSH_CONF) if -f $DRBLPUSH_CONF;
	open(CONFIG_FILE,">$DRBLPUSH_CONF") or die "$lang_deploy{\"failed_to_open_file\"} \"$DRBLPUSH_CONF\"\n";

	# get domain name
	# If we can find the one in system, use it as the default one
	if ( $dnsdomain_sys && "$dnsdomain_sys" ne "localdomain" ) {
	  $DEFAULT_DOMAINNAME="$dnsdomain_sys";
        }
        print "$delimiter{\"dash_line\"}\n".
              "$lang_deploy{\"domain_prompt\"}\n".
	      "[$DEFAULT_DOMAINNAME] ";
        while (<STDIN>) {
           chomp;
           $dnsdomain_sys=$_;
	   if ( "$dnsdomain_sys" =~ / |\/|\\/ ) {
  	     print "\" \" ($lang_text{\"space\"}), \"/\", $lang_text{\"or\"} \"\\\" $lang_deploy{\"not_allowed_domainname\"} $lang_deploy{\"enter_it_again\"}!\n".
	           "[$DEFAULT_DOMAINNAME] ";
           } else {
	     # if empty, use default name
             if ($dnsdomain_sys eq "") { $dnsdomain_sys="$DEFAULT_DOMAINNAME"; }
	     print "$lang_deploy{\"set_domain_as\"} $dnsdomain_sys\n";
             last;
           }
        }

	# get nis domain name
	# If we can find the one in system, use it as the default one.
	# We will not use "localdomain" "nisdomainname: Local domain name not set" (on Fedora 13, when nisdomainname is not set, it is shown as that) and "(none)"
	if ( $nisdomain_sys && "$nisdomain_sys" !~ /^(localdomain|nisdomainname: Local domain name not set|\(none\))$/i ) {
	  $DEFAULT_NISDOMAINNAME="$nisdomain_sys";
        }
        print "$delimiter{\"dash_line\"}\n".
              "$lang_deploy{\"nisdomain_prompt\"}\n".
	      "[$DEFAULT_NISDOMAINNAME] ";
        while (<STDIN>) {
           chomp;
           $nisdomain_sys=$_;
	   if ( "$nisdomain_sys" =~ / |\/|\\|\.|^[0-9]/ ) {
  	     print "\" \" ($lang_text{\"space\"}), \"/\", \".\", \"\\\" $lang_text{\"or\"} \"$lang_word{\"initial_digit\"}\" $lang_deploy{\"not_allowed_nisdomain_sys\"} $lang_deploy{\"enter_it_again\"}!\n".
	           "[$DEFAULT_NISDOMAINNAME] ";
           } else {
	     # if empty, use default name
             if ($nisdomain_sys eq "") { $nisdomain_sys="$DEFAULT_NISDOMAINNAME"; }
	     print "$lang_deploy{\"set_domain_as\"} $nisdomain_sys\n";
             last;
           }
        }

	# get client hostname prefix
        print "$delimiter{\"dash_line\"}\n".
              "$lang_deploy{\"enter_client_hostname_prefix\"}\n".
	      "[$client_hostname_prefix_default[0]] ";
           while (<STDIN>) {
              chomp;
              $client_hostname_prefix=$_;
	      if ( "$client_hostname_prefix" =~ / |\/|\\|\./ ) {
		# "-" should be ok, but we need to parse the /etc/dhcpd.conf
		# then if make it like fc1-1=00:2A:00:AB:CD:EF, run
		#  fc1-1=00:2A:00:AB:CD:EF in shell will fail. So we skip
		#  "-"
  	        print "\" \" ($lang_text{\"space\"}), \"/\", \".\", \"\\\" $lang_text{\"or\"} \"$lang_word{\"initial_digit\"}\" $lang_deploy{\"not_allowed_hostname\"} $lang_deploy{\"enter_it_again\"}!\n".
	              "[$client_hostname_prefix_default[0]] ";
              } else {
	        # if empty, use default name
                if ($client_hostname_prefix eq "") {
                  $client_hostname_prefix="$client_hostname_prefix_default[0]";
                }
                print "$lang_deploy{\"set_client_hostname_prefix\"} $client_hostname_prefix\n".
                "$delimiter{\"dash_line\"}\n";
                last;
              }
           }
        # try to find all the NIC for clients, i.e. eth1, eth2...
        foreach my $ethx (@ethernet_list) {
	 print "Finding the IP address for $ethx...\n" if $verbosity >=2;
	 chomp($nic_ethx_ip=`drbl-get-ipadd $ethx`);
	 chomp($nic_ethx_netmask=`drbl-get-netmask $ethx`);
   	 if ( $nic_ethx_ip ) {
	   # Specially, we do not want the alias interface, such as:eth0:1
           my $IP=`drbl-get-ipadd $ethx`;
	   chomp($IP);
           if ( ! $IP ) {
             print "The IP address of $ethx was not found!\n".
	           "$lang_deploy{\"we_will_skip\"} $ethx!\n";
           } else {
  	     print "$ethx: IP address $IP, netmask $nic_ethx_netmask\n";
  	     push @ethernet_sys, $ethx;
           }

         }
        }
	if ( @ethernet_sys <= 0 ) {
 	  print "$lang_deploy{\"no_NIC_setup\"}\n".
	        "$lang_deploy{\"we_can_NOT_continue\"}\n";
	  exit;
	} else {
       	  print "$lang_deploy{\"configured_nic\"} ".
	         colored ("@ethernet_sys \n", "$color_warn");
          print "$delimiter{\"dash_line\"}\n";

	  # Find the ethernet port connected to WAN.
	  print "Finding the available public IP address...\n" if $verbosity >=2;
	  chomp($public_ip_addr=`get-all-nic-ip -a`);
	  chomp($public_ip_port=`get-all-nic-ip -p`);
	  if ($public_ip_port) {
            print "$lang_deploy{\"ethernet_port_for_internet\"} $public_ip_port\n";
            @ethernet_sys = grep { $_ ne "$public_ip_port" } @ethernet_sys;
            print "$lang_deploy{\"ethernet_port_for_DRBL\"} ".
	          colored ("@ethernet_sys \n", "$color_warn");

          }else{
            my $private_eth_ports_;
            chomp($private_eth_ports_=`get-all-nic-ip -t`);
            my @private_eth_ports=split(/ /,$private_eth_ports_);
	    my $guess_uplink_port;
	    # we just want one port, so use "head -n 1" to get the 1st one.
            chomp($guess_uplink_port=`PATH=$PATH:/sbin/:/usr/sbin route -n | awk '/^0.0.0.0/ {print \$8}' | sort | head -n 1`);
            print "$lang_deploy{\"unable_to_find_public_IP\"}\n".
                  "$lang_deploy{\"for_internet_access_prompt\"}\n".
		  "$lang_deploy{\"available_eth_ports\"}:\n";
            foreach my $ethx (@private_eth_ports){
                  my $IP=`drbl-get-ipadd $ethx`;
	          chomp($IP);
                  print "$ethx ($IP), ";
            }
	    print "\n";
            print "[$guess_uplink_port] ";
            while (<STDIN>) {
              chomp;
	      $pub_ans=$_;
              if ($pub_ans eq "") { $pub_ans="$guess_uplink_port"; }
	      foreach my $k (@private_eth_ports) {
	        if ( "$pub_ans" eq "$k" ) {
	          # if empty, use default name
	          $pub_port_NAT=$pub_ans;
                  last;
                }
	      }
	      if ( $pub_port_NAT ) {
		 last;
              }else{
  	         print "\"$pub_ans\" $lang_deploy{\"is_not_in_the_lists\"} (@private_eth_ports). $lang_deploy{\"enter_it_again\"}!\n";
              }
            }
	    print "$lang_deploy{\"the_eth_port_you_choose_for_wan\"}: ".
	          colored ("$pub_port_NAT\n", "$color_warn");
            # Exclude uplink port, so @ethernet_sys will contain only ports connected to DRBL clients.
            @ethernet_sys = grep { $_ ne "$pub_port_NAT" } @ethernet_sys;
	    if (@ethernet_sys) {
              print "$lang_deploy{\"ethernet_port_for_DRBL\"} ".
	          colored ("@ethernet_sys \n", "$color_warn");
            }
          }
	  # if not ethernet port is available for DRBL, use $pub_port_NAT.
	  if ( @ethernet_sys <= 0 ) {
	    # Since only one port is available, we will use this only one to provide services for client. Give WARNING!
	    if (!$continue_with_one_port) {
	      print colored ("$lang_deploy{\"only_one_network_card_in_system\"}\n", "$color_warn").
                    colored ("$lang_deploy{\"are_you_sure_you_want_to_continue\"}\n", "$color_warn").
	            "[y/N] ";
              chomp($continue_with_one_port=<STDIN>);
	    }
            SWITCH: for ($continue_with_one_port) {
              /^y$|^yes$/i && do {
	        # 2 cases: (1) only one public IP address port (public_ip_port) (2) only one private IP address port connected to WAN via NAT (pub_port_NAT)
		if ($pub_port_NAT) {
                  @ethernet_sys = ("$pub_port_NAT");
		} elsif ($public_ip_port) {
                  @ethernet_sys = ("$public_ip_port");
		}
		$one_ethernet_port_server="yes";
                last SWITCH;
              };
              /.*/ && do {
	        print "$lang_deploy{\"program_stop\"}\n";
                exit (1);
                last SWITCH;
              };
            }
          }
	  # Final check before using ethernet port
	  if ( @ethernet_sys <= 0 ) {
 	    print "$lang_deploy{\"no_NIC_setup\"}\n".
	          "$lang_deploy{\"we_can_NOT_continue\"}\n";
	    exit;
	  }
	  # Checking if class A/B private IP ? If so, set warning about multicast clonezilla
          # for($i=0;$i<=$#ethernet_sys;$i++) {
	  #  my $ethx="$ethernet_sys[$i]";
          #  my $IP=`drbl-get-ipadd $ethx`;
	  #  chomp($IP);
	  #  if ( "$IP" =~ /^(172\.(1[6-9]|2[0-9]|3[01])\..*|10\..*)/ ) {
          #    # Class A: 10.0.0.0 - 10.255.255.255
          #    # Class B: 172.16.0.0  - 172.31.255.255
	  #    print "$delimiter{\"star_line\"}\n";
	  #    #print "Found class A or B private IP \"$IP\" in $ethx for your DRBL system! ".
	  #    #colored ("$lang_deploy{\"class_c_IP_for_multicast_clonezilla\"}\n", "$color_warn");
	  #    #print "$delimiter{\"star_line\"}\n".
	  #    #      "$lang_deploy{\"press_enter_to_continue\"}";
	  #    #      chomp($line=<STDIN>);
          #  }
	  #};
	  #print "$delimiter{\"star_line\"}\n";
        }
        if ($one_ethernet_port_server eq "yes") {
	  # Ask if proxy DHCP when there is existing DHCP
	  # Detect DHCP service first
	  my $detect_dhcp_rlt1=256;
          while ($detect_dhcp_rlt1 == 256) {
	     $detect_dhcp_rlt1=system("drbl-find-dhcp-srv -i $ethernet_sys[0] $drblpush_wd/dhcp-detect.tmp");
	     if ($detect_dhcp_rlt1 == 256) {
               print "\n$delimiter{\"star_line\"}\n";
	       print colored ("$lang_deploy{\"failed_to_detect_dhcp_service\"}\n", "$color_warn").
                              "$lang_deploy{\"do_you_want_to_try_it_again\"}\n".
                              "[Y/n] ";
	       chomp(my $try_again=<STDIN>);
	       if ($try_again eq "n" || $try_again eq "N" || $try_again eq "no" || $try_again eq "NO") {
	         $detect_dhcp_rlt1=0;
               }
             }
          }
	  # Only when $drblpush_wd/dhcp-detect.tmp exists we will continue this
	  chomp($DHCPOFFER_eth=`. $drblpush_wd/dhcp-detect.tmp; echo \$DHCPOFFER_eth`);
	  chomp($DHCPOFFER_siaddr=`. $drblpush_wd/dhcp-detect.tmp; echo \$DHCPOFFER_siaddr`);
	  chomp($DHCPOFFER_yiaddr=`. $drblpush_wd/dhcp-detect.tmp; echo \$DHCPOFFER_yiaddr`);
	  if ($DHCPOFFER_siaddr) {
	      print "$delimiter{\"star_line\"}\n";
	      print colored ("$lang_deploy{\"found_dhcp_service_on_nic\"}: $DHCPOFFER_eth\n", "$color_warn").
                    colored ("$lang_deploy{\"do_you_want_to_lease_ip_addr_from_existing_dhcp_srv\"}: $DHCPOFFER_siaddr\n", "$color_warn").
	            colored ("$lang_deploy{\"will_use_available_ip_addr_from_dhcp_srv\"}\n", "$color_warn").
	            colored ("$lang_deploy{\"note_you_have_to_make_sure_enough_no_of_ip_addr\"}\n", "$color_warn").
	            "[Y/n] ";
              chomp($use_proxy_dhcp=<STDIN>);
	  }
          SWITCH: for ($use_proxy_dhcp) {
            /^n$|^no$/i && do {
	      # Format the variable use_proxy_dhcp
	      $use_proxy_dhcp="no";
	      print colored ("Do not use proxy DHCP.\n","$color_warn");
              last SWITCH;
            };
            /.*/ && do {
	      # Format the variable use_proxy_dhcp
	      $use_proxy_dhcp="yes";
	      print colored ("Use proxy DHCP. Adding virtual network drbl0...\n","$color_warn");
	      system("drbl-add-vir-netdev $ethernet_sys[0] drbl0");
	      my $detect_dhcp_rlt2=256;
              while ($detect_dhcp_rlt2 == 256) {
	         $detect_dhcp_rlt2=system("drbl-find-dhcp-srv -i drbl0 $drblpush_wd/dhcp-detect-vir0.txt");
	         if ($detect_dhcp_rlt2 == 256) {
                   print "\n$delimiter{\"star_line\"}\n";
	           print colored ("$lang_deploy{\"failed_to_detect_dhcp_service\"}\n", "$color_warn").
                                  "$lang_deploy{\"do_you_want_to_try_it_again\"}\n".
                                  "[Y/n] ";
	           chomp(my $try_again=<STDIN>);
	           if ($try_again eq "n" || $try_again eq "N" || $try_again eq "no" || $try_again eq "NO") {
	             $detect_dhcp_rlt2=0;
                   }
                 }
              }
              # Reset variables before loading them.
              $DHCPOFFER_eth="";
              $DHCPOFFER_siaddr="";
              $DHCPOFFER_yiaddr="";
              $DHCPOFFER_prefix="";
	      chomp($DHCPOFFER_eth=`. $drblpush_wd/dhcp-detect-vir0.txt; echo \$DHCPOFFER_eth`);
	      chomp($DHCPOFFER_siaddr=`. $drblpush_wd/dhcp-detect-vir0.txt; echo \$DHCPOFFER_siaddr`);
	      chomp($DHCPOFFER_yiaddr=`. $drblpush_wd/dhcp-detect-vir0.txt; echo \$DHCPOFFER_yiaddr`);
	      chomp($DHCPOFFER_prefix=`. $drblpush_wd/dhcp-detect-vir0.txt; echo \$DHCPOFFER_prefix`);
	      if ($DHCPOFFER_yiaddr) {
	        if (!$DHCPOFFER_prefix) {
	          chomp($DHCPOFFER_prefix=`LC_ALL=C ip -o -f inet addr show $ethernet_sys[0] | awk -F" " '{print \$4}' | awk -F"/" '{print \$2}' | head -n 1`);
		}
                system("ip addr add $DHCPOFFER_yiaddr/$DHCPOFFER_prefix dev drbl0");
		# TODO: check if new dirvir0 exists.
		# TODO: Write system config file for virtual network card (Debian/Ubuntu, Fedora...)
                system("perl -p -i -e \"s/^use_existing_dhcp_srv=.*/use_existing_dhcp_srv=yes/g\" $drbl_syscfg/drbl.conf");
		# Put new virtual network card in $ethernet_sys
  	        push @ethernet_sys, drbl0;
		# Since virtual network card is pushed, now we should remove $pub_port_NAT or $public_ip_port
		if ($pub_port_NAT) {
                  @ethernet_sys = grep { $_ ne "$pub_port_NAT" } @ethernet_sys;
		} elsif ($public_ip_port) {
                  @ethernet_sys = grep { $_ ne "$public_ip_port" } @ethernet_sys;
		}
	      }
              last SWITCH;
            };
          }
        }

# detect the mac address
    # Only when there are two or more ethernet ports we should collect MAC.
    if ( $one_ethernet_port_server eq "no" ) {
      print "$delimiter{\"star_line\"}\n".
            "$lang_deploy{\"collect_MAC_prompt\"}\n".
            "[y/N] ";
      chomp($line=<STDIN>);
      SWITCH: for ($line) {
              /^y$|^yes$/i && do {
          	  $collect_mac="yes";
                    print "$delimiter{\"star_line\"}\n".
                          "$lang_deploy{\"ok_let_do_it\"}\n";
                    my $whoiam = `LC_ALL=C id -nu`;
                    chomp($whoiam);
                    if ("$whoiam" eq "root") {
                      system("LC_ALL=C drbl-collect-mac -n -l $language @ethernet_sys");
                      print colored ("$lang_deploy{\"saved_mac_address_files_in_etc\"}\n", "$color_warn");
                    }else{
                       print "$lang_deploy{\"you_are_not_root\"},\n".
                             "$lang_word{\"please_enter\"} ". colored("$lang_word{\"root_passwd\"} ","$color_warn"). "to collect those MAC addresses...\n";
                       my $su_rlt=system("LC_ALL=C su -c \"drbl-collect-mac @ethernet_sys\" root");
                       while ($su_rlt == 256) {
                              $su_rlt=system("LC_ALL=C su -c \"drbl-collect-mac @ethernet_sys\" root");
                       }
                    }
          	  last SWITCH;
              };
              /.*/ && do {
          	  $collect_mac="no";
          	  last SWITCH;
              };
      }
    }

    print "$delimiter{\"star_line\"}\n".
          "$lang_deploy{\"ok_let_continue\"}\n".
          "$delimiter{\"star_line\"}\n";

# ask user to input client no.
	my @ip_sys_start;
	my @ip_sys_end;
        my @total_client_no;
        for($i=0;$i<=$#ethernet_sys;$i++) {
	 $ethx="$ethernet_sys[$i]";
          # Try to get setting from system also
          # get the ipaddress of NIC "eth1, eth2..."
          my $ip_sys_tmp;
          my $netmask_sys_tmp;
          chomp($ip_sys_tmp=`drbl-get-ipadd $ethx`);
          chomp($netmask_sys_tmp=`drbl-get-netmask $ethx`);
	  # We must get the static IP for this NIC, NO DHCP...
          if ( "$ip_sys_tmp" eq "" ) {
	    print "$delimiter{\"star_line\"}\n".
  	          "$lang_deploy{\"unable_to_get_ethx_IP\"} ".
	           colored("$ethx \n","$color_fail").
            	  "$lang_deploy{\"program_stop\"}\n";
            exit (1);
          };

	  # Find the available start IP which will not conflict with the server
          my $ip_hostmin = `drbl-ipcalc $ip_sys_tmp $netmask_sys_tmp | awk -F' ' '/^HostMin:/ {print \$2}'`;
	  chomp($ip_hostmin);
	  print "Hostmin: $ip_hostmin\n";
	  # Find the max number of the class
          my $hostmax_no = `drbl-ipcalc $ip_sys_tmp $netmask_sys_tmp | grep -Ew "^Hosts/Net:" | awk -F":" '{print \$2}' | awk -F" " '{print \$1}'`;
	  chomp($hostmax_no);
          my @ip_sys_sp=split(/\./,$ip_hostmin);
          $ip_sys_prefix[$i]="$ip_sys_sp[0].$ip_sys_sp[1].$ip_sys_sp[2]";
          $ip_sys[$i]=$ip_sys_tmp;

	  if ( $use_proxy_dhcp eq "no" ) {
	    # Only when it's not proxy mode we will ask about using fixed IP address
  	    print "$lang_deploy{\"fix_eth_IP_prompt\"} ".
	           colored("$ethx","$color_warn").
	           " ?\n".
	    "[y/N] ";
	    chomp($MAC=<STDIN>);
	  } else {
	    $MAC="no";
	  }
          my $mac_f_tmp="";
	  if ($MAC eq "y" || $MAC eq "Y" || $MAC eq "yes" || $MAC eq "YES") {
            # User wants to fix the IP addresses for DRBL clients
	    print "$delimiter{\"star_line\"}\n".
	          "$lang_deploy{\"MAC_file_prompt\"} $ethx.\n".
		  "[macadr-$ethx.txt] ";
            while (<STDIN>) {
	      chomp;
	      if ( $_ eq "" ) {
	        $mac_f_tmp="macadr-$ethx.txt";
	      }else{
	        $mac_f_tmp=$_;
	      }

              # 2 cases filename user entered (1) without path (2) with path
              # we will try both cases, and copy the file to working dir.
              $MAC_file[$i]=`basename $mac_f_tmp 2>/dev/null`;
              chomp($MAC_file[$i]);
              my $mac_dir=`dirname $mac_f_tmp 2>/dev/null`;
              chomp($mac_dir);
              # if user does not specify the path, then it is the original wd
              if ( $mac_dir eq "." ) { $mac_dir="$orig_wd"; }
              print "MAC_file[$i], mac_dir: $MAC_file[$i], $mac_dir\n" if $verbosity >= 2;

              # (1) w/o path: copy the entered file from orig_wd if they exist
              # this is the case if user specified file like "mac1.txt"
              # (2) whith path: copy the entered file if they exist
              # this is the case if user specified file like "/root/mac1.txt"
              system("[ -f $mac_dir/$MAC_file[$i] ] && cp -f $mac_dir/$MAC_file[$i] ./");

              # check MAC address files
              check_MAC_file(".","$MAC_file[$i]");

              my $range_start_default = `echo $ip_hostmin | awk -F"." '{print \$4}'`;
	      chomp($range_start_default);

              # get the client no from user input
	      # 1st, get the initial value of the last set of digits in the IP address in this subnet
	      print "$delimiter{\"star_line\"}\n".
	            "$lang_deploy{\"IP_start_prompt\"} $ethx.\n",
		    "[$range_start_default] ";

              unless ( $range_start[$i] ) {
                 while (<STDIN>) {
                   chomp;
	           my $start_input=$_;
                   if ($start_input eq "") {
                     $range_start[$i]=$range_start_default;
	             last;
	           } elsif ( $start_input =~ /[^0-9]/ ) {
	               print "$lang_deploy{\"not_initial_value\"}\n";
                   } else {
	               $range_start[$i]=$start_input;
	               last;
                   }
                 }
              }
	      # use wc -l to count the lines of file user input
              # we use the MAC file in working dir ($MAC_file[$i]) so it been
              # processed by check_MAC_file. Ex. the space line is stripped.
              chomp($line=`LC_ALL=C cat $MAC_file[$i] 2>/dev/null | wc -l |tr -d \" \" `);
              $range_end[$i]=$range_start[$i] + $line - 1;
	      if ($line >= $hostmax_no) {
	        print colored ("The file \"$mac_dir/$MAC_file[$i]\" you set for the clients connected to $ethx is empty or invalid.\nTotal number of clients in file: $line.\nMax number in this subnet: $hostmax_no.\nPlease enter the filename again, or press \"ctrl-c\" to quit!\n", "$color_warn");
              } else {
                $range_end[$i]=$range_start[$i] + $line - 1;
	        last;
              }
	    }
	  } else {
            # User wants to use floating IP addresses for DRBL clients
	    print "$delimiter{\"star_line\"}\n".
	          "$lang_deploy{\"range_prompt\"}\n";
            my $range_start_default = `echo $ip_hostmin | awk -F"." '{print \$4}'`;
	    chomp($range_start_default);

            # user does NOT want to fix the IP address for DRBL client
            # get the client no from user input
	    print "$delimiter{\"star_line\"}\n".
	          "$lang_deploy{\"IP_start_prompt\"} $ethx.\n",
		  "[$range_start_default] ";
            unless ( $range_start[$i] ) {
               while (<STDIN>) {
                 chomp;
	         my $start_input=$_;
                 if ($start_input eq "") {
                   $range_start[$i]=$range_start_default;
	           last;
	         } elsif ( $start_input =~ /[^0-9]/ ) {
	             print "$lang_deploy{\"not_initial_value\"}\n";
                 } else {
	             $range_start[$i]=$start_input;
	             last;
                 }
               }
            }
            # count the clients no which already exist to prompt user
            my $client_no;
	    if ( ! $assign_client_no_each_port ) {
              $client_no=`LC_ALL=C unalias ls 2> /dev/null; ls -d /tftpboot/nodes/$ip_sys_prefix[$i].* 2>/dev/null |wc -w|sed -e "s/ //g"`;
              chomp($client_no);
              # if 0, set the default no for user
	      if ($client_no eq "0") { $client_no="$DEFAULT_CLIENT_NO_EACH_PORT";}
            } else {
              $client_no=$assign_client_no_each_port;
            }
            print "client_no:$client_no\n" if $verbosity >=2;
	    print "$delimiter{\"star_line\"}\n".
  	          "$lang_deploy{\"client_number_connected_to_eth\"} $ethx ?\n".
                  "$lang_deploy{\"enter_the_no\"}: \n".
                  "[$client_no] ";
            while (<STDIN>) {
	      chomp;
	      my $line=$_;
	      if ($line eq "") { $line=$client_no;}
	      if ($line >= $hostmax_no) {
	        print colored ("Total number of clients in file: $line.\nMax number in this subnet: $hostmax_no.\nPlease enter the client number again, or press \"ctrl-c\" to quit!\n", "$color_warn");
              } else {
                $range_end[$i]=$range_start[$i] + $line - 1;
	        last;
	      }
	    }
	  }
	  # List all the IP address, and get the last one.
	  $total_client[$i]=$range_end[$i]-$range_start[$i]+1;
	  $ip_sys_start[$i]=$ip_sys_prefix[$i].".".$range_start[$i];
          chomp($ip_sys_end[$i]=`drbl-ipcalc-list -c $total_client[$i] $ip_sys_start[$i] $netmask_sys_tmp | head -n $total_client[$i] | tail -n 1`);

          if ( ! $MAC_file[$i] ){
            # use the range for clients.
	    print "$delimiter{\"star_line\"}\n".
  	          "$lang_deploy{\"set_the_IP_connected_to_eth\"} ".
                  colored ("$ethx $lang_text{\"as\"}: $ip_sys_start[$i] - $ip_sys_end[$i]\n","$color_warn").
                  "$lang_text{\"Accept\"} ? [Y/n] ";
	  }else{
            # use the fixed IP address for clients.
	    print "$delimiter{\"star_line\"}\n".
	          "$lang_deploy{\"filename_you_set\"} \"$MAC_file[$i]\".\n".
		  "$lang_deploy{\"client_no_in_MAC_file\"} $line.\n".
  	          "$lang_deploy{\"set_the_IP_connected_to_eth\"} $ethx $lang_deploy{\"by_MAC_file\"} ".
                  colored ("$ethx $lang_text{\"as\"}: $ip_sys_start[$i] - $ip_sys_end[$i]\n","$color_warn").
                  "$lang_text{\"Accept\"} ? [Y/n] ";
          }

	  chomp($line=<STDIN>);
	  if ($line eq "n" || $line eq "N" || $line eq "no" || $line eq "NO") {
	   print "$delimiter{\"exclamation_line\"}\n".
	         "$lang_deploy{\"let_restart_it_again\"}\n";
	   redo;
	  }
	  else {
	   print "$delimiter{\"star_line\"}\n".
	         "$lang_deploy{\"ok_let_continue\"}\n";
          }
	}

	# print the schematic network
        my $PUB_NIC;
        my $IP_PUB_NIC;
	if ( $public_ip_port ) {
          $PUB_NIC=$public_ip_port;
	  $IP_PUB_NIC=$public_ip_addr;
        }else{
          $PUB_NIC=$pub_port_NAT;
          chomp($IP_PUB_NIC=`drbl-get-ipadd $pub_port_NAT`);
	}
	print "$delimiter{\"star_line\"}\n".
       	      "$lang_deploy{\"layout_for_DRBL\"} \n".
  	      "$delimiter{\"star_line\"}\n";
        print color "$color_warn";
        print
"          NIC    NIC IP                    Clients\n".
"+-----------------------------+\n".
"|         DRBL SERVER         |\n".
"|                             |\n".
"|    +-- [$PUB_NIC] $IP_PUB_NIC +- to WAN\n".
"|                             |\n";
          for($i=0;$i<=$#ethernet_sys;$i++) {
	   $ethx="$ethernet_sys[$i]";
	   my $grp=$ethx;
	   # extract group for ethx, i.e. group 1 for eth1, group 3 for eth3...
	   # For interface like vmnet1, we will not extract that so that the
	   # hostname will not conflict.
	   $grp=~ s/eth//;
	   # get the total client number. total_client[$i] is only for those connecting to ethx
           $total_client_no += $total_client[$i];
	   #
           print
"|    +-- [$ethx] $ip_sys[$i] +- to clients group $grp [ $total_client[$i] clients, their IP \n".
"|                             |            from $ip_sys_start[$i] - $ip_sys_end[$i]]\n";
          }

	  print
"+-----------------------------+\n";
          print color 'reset';
          print
		"$delimiter{\"star_line\"}\n";

        print "Total clients: ".
	      colored ("$total_client_no\n", "$color_warn").
              "$delimiter{\"star_line\"}\n".
              "$lang_deploy{\"press_enter_to_continue\"}";
              chomp($line=<STDIN>);

	# Ask user if DRBL SSI mode ?
	print "$delimiter{\"star_line\"}\n";
	if ( ! $drbl_mode ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"which_drbl_mode_for_client\"}\n".
	        "[0] ";
          chomp($drbl_mode=<STDIN>);
        }
        SWITCH: for ($drbl_mode) {
          /^[[:space:]]*1[[:space:]]*$/ && do {
            $drbl_mode="drbl_ssi_mode";
            print "$lang_deploy{\"drbl_ssi_mode_is_set\"}\n".
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
	  };
          /^[[:space:]]*2[[:space:]]*$/ && do {
            $drbl_mode="none";
	    # since no diskless service for client in the system,
	    # set some default value to avoid asking laster.
	    $swap_create="no";
	    $client_startup_mode="2";  # text mode
            $set_client_root_passwd="no";
            $set_DBN_client_audio_plugdev="no";
            $set_client_alias_IP="no";
            $open_thin_client_option="no";
            print colored ("$lang_deploy{\"no_drbl_mode_in_system\"}\n", "$color_warn").
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
	  };
          /.*/ && do {
            $drbl_mode="full_drbl_mode";
            print "$lang_deploy{\"full_drbl_mode_is_set\"}\n".
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
          };
        }
	# Ask user if clonezilla box mode ?
	if ( ! $clonezilla_mode ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"which_clonezilla_mode_for_client\"}\n".
	        "[0] ";
          chomp($clonezilla_mode=<STDIN>);
        }
        SWITCH: for ($clonezilla_mode) {
          /^[[:space:]]*1[[:space:]]*$/ && do {
            $clonezilla_mode="clonezilla_box_mode";
            print "$lang_deploy{\"clonezilla_box_mode_is_set\"}\n".
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
	  };
          /^[[:space:]]*2[[:space:]]*$/ && do {
            $clonezilla_mode="none";
	    # since no clonezilla in the system,
	    # set some default value to avoid asking laster.
            $ocs_img_repo_dir="$ocs_img_repo_dir_default";
            print  colored ("$lang_deploy{\"no_clonezilla_in_system\"}\n", "$color_warn").
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
	  };
          /^[[:space:]]*3[[:space:]]*$/ && do {
            $clonezilla_mode="clonezilla_live_mode";
            print "$lang_deploy{\"clonezilla_live_mode_is_set\"}\n".
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
	  };
          /.*/ && do {
            $clonezilla_mode="full_clonezilla_mode";
            print "$lang_deploy{\"full_clonezilla_mode_is_set\"}\n".
                  "$delimiter{\"star_line\"}\n";
            last SWITCH;
          };
        }
	# Ask client's CPU arch when running Clonezilla job with Clonezilla live
	if ( "$run_drbl_ocs_live_prep" eq "yes" ) {
          if ( "$clonezilla_mode" eq "clonezilla_live_mode" ) {
             if ( ! "$live_client_branch" ) {
  	     print "$delimiter{\"star_line\"}\n".
  	           "$lang_deploy{\"which_clonezilla_live_branch\"}\n".
  	           "[2] ";
  	     chomp($live_client_branch=<STDIN>);
             }
             if ( ! "$live_client_cpu_mode" ) {
               if ( "$live_client_branch" eq "0" || "$live_client_branch" eq "1" ) {
  	       print "$delimiter{\"star_line\"}\n".
  	             "$lang_deploy{\"which_live_client_cpu_mode\"}\n".
  	             "[2] ";
  	       chomp($live_client_cpu_mode=<STDIN>);
               }else{
                # For Ubuntu-based Clonezilla live, different arch is not available.
		# Only amd64 is available in Ubuntu >= 19.10
  	        print "$lang_deploy{\"from_ubuntu_1910_only_amd64_is_available\"}\n";
  	       }
             }
  	}
  	# Format the input number as text
          SWITCH: for ($live_client_branch) {
            /^[[:space:]]*0[[:space:]]*$/ && do {
              $live_client_branch="stable";
              last SWITCH;
          };
            /^[[:space:]]*1[[:space:]]*$/ && do {
              $live_client_branch="testing";
              last SWITCH;
          };
            /^[[:space:]]*3[[:space:]]*$/ && do {
              $live_client_branch="alternative_testing";
              last SWITCH;
          };
            /.*/ && do {
              $live_client_branch="alternative";
              last SWITCH;
            };
          }
  	if ( $live_client_cpu_mode ) {
  	  print "$delimiter{\"star_line\"}\n";
  	  print "$lang_deploy{\"live_client_branch_set\"}: $live_client_branch\n";
  	}
  	# Format the input number as text
         if ( "$live_client_branch" eq "stable" || "$live_client_branch" eq "testing" ) {
          # Normal Clonezilla live, i686, i686-pae and amd64 exist
          SWITCH: for ($live_client_cpu_mode) {
            /^[[:space:]]*0[[:space:]]*$/ && do {
              $live_client_cpu_mode="i686";
              last SWITCH;
          };
            /^[[:space:]]*1[[:space:]]*$/ && do {
              $live_client_cpu_mode="i686-pae";
              last SWITCH;
          };
            /^[[:space:]]*2[[:space:]]*$/ && do {
              $live_client_cpu_mode="amd64";
              last SWITCH;
          };
            /.*/ && do {
              $live_client_cpu_mode="amd64";
              last SWITCH;
            };
          }
         }else{
          # Alternative Clonezilla live, only amd64 exists from Ubuntu >= 19.10
          $live_client_cpu_mode="amd64";
         }
         if ( $live_client_cpu_mode ) {
           print "$delimiter{\"star_line\"}\n";
           print "$lang_deploy{\"live_client_cpu_arch_is_set\"}: $live_client_cpu_mode\n";
         }
        }

	if ( "$drbl_mode" eq "none" && "$clonezilla_mode" eq "none" ) {
  	  print colored ("$lang_deploy{\"both_drbl_clonezilla_are_none\"}\n", "$color_warn");}
	# Ask user what's clonezilla image's repository ?
	#
	if ( ! $ocs_img_repo_dir ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"where_is_ocs_img_repo_dir\"}\n".
	        "[$ocs_img_repo_dir_default] ";
          while (<STDIN>) {
             chomp;
             $ocs_img_repo_dir=$_;
	     if ( "$ocs_img_repo_dir" =~ /\/mnt$|\/media$|\/tmp$/ ) {
	     print "$ocs_img_repo_dir $lang_deploy{\"not_allowed_ocs_img_repo_dir\"} $lang_deploy{\"enter_it_again\"}!\n".
	           "[$ocs_img_repo_dir_default] ";
             } else {
	       # if empty, use default name
               if ($ocs_img_repo_dir eq "") { $ocs_img_repo_dir="$ocs_img_repo_dir_default"; }
	       print colored ("Directory for Clonezilla saved images: $ocs_img_repo_dir\n", "$color_warn");
               last;
             }
          }
        }

        # ask if use need local HD space as swap file ?
	if ( ! $swap_create ) {
	  print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"swap_prompt\"}\n".
	        "[Y/n] ";
          chomp($swap_create=<STDIN>);
	}
	SWITCH: for ($swap_create) {
	  /^n$|^no$/i && do {
            $localswapfile="no";
            last SWITCH;
	  };
	  /.*/ && do {
            $localswapfile="yes";
	    print "$delimiter{\"star_line\"}\n".
                  "$lang_deploy{\"try_to_create_swap\"}\n".
                  "$delimiter{\"dash_line\"}\n".
                  "$lang_deploy{\"max_swap_size\"}\n".
	          "[$MAXSWAPSIZE_DEFAULT] ";
            chomp($maxswapsize=<STDIN>);
	    if ( "$maxswapsize" eq "" ) {
	          $maxswapsize="$MAXSWAPSIZE_DEFAULT";
	          print colored ("maxswapsize=$maxswapsize\n", "$color_warn");
            }
            last SWITCH;
	  };
        }

	# Ask which mode is preferred for clients
	print "$delimiter{\"star_line\"}\n";
	if ( ! $client_startup_mode ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"mode_for_client_init\"}\n".
	        "[1] ";
          chomp($client_startup_mode=<STDIN>);
        }
        if ($client_startup_mode eq "2") {
            $CLIENT_INIT="text";
            print "$lang_deploy{\"client_text_mode\"}\n".
                  "$delimiter{\"star_line\"}\n";
	}else{
            $CLIENT_INIT="graphic";
            print "$lang_deploy{\"client_graphic_mode\"}\n".
                  "$delimiter{\"star_line\"}\n";
            print "$delimiter{\"dash_line\"}\n".
                  "$lang_deploy{\"login_mode_for_client\"}\n".
	          "[0] ";
            chomp($login_gdm_opt=<STDIN>);
            if ($login_gdm_opt eq "1") {
                $LOGIN_GDM_OPT="auto_login";
		set_autologin_passwd;
                print "$lang_deploy{\"auto_login\"}\n".
                      "$delimiter{\"star_line\"}\n";
                print "[$total_client_no] $lang_deploy{\"created_account_for_auto_login\"}".
                      " \"$AUTO_LOGIN_ID_PASSWD\"\n";
            } elsif ($login_gdm_opt eq "2") {
                $LOGIN_GDM_OPT="timed_login";
                print "$delimiter{\"dash_line\"}\n".
                      "$lang_deploy{\"time_for_countdown\"}\n".
	              "[$TIMED_GDM_TIME_DEFAULT] ";
                chomp($timed_time=<STDIN>);
                if ($timed_time eq "") {
                   $TIMED_LOGIN_TIME = "$TIMED_GDM_TIME_DEFAULT";
                }else{
                   $TIMED_LOGIN_TIME = $timed_time;
                }
                print "$lang_deploy{\"timed_login_prompt\"} $TIMED_LOGIN_TIME $lang_text{\"seconds\"}.\n".
                      "$delimiter{\"star_line\"}\n";
                print "[$total_client_no] $lang_deploy{\"created_account_for_auto_login\"}".
                      " \"$AUTO_LOGIN_ID_PASSWD\"\n";
            } else {
                $LOGIN_GDM_OPT="login";
                print "$lang_deploy{\"normal_login_prompt\"}\n".
                      "$delimiter{\"star_line\"}\n";
            }
        }
	# Ask if user want to set the root password of clients
	if ( ! $set_client_root_passwd ){
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"set_client_root_passwd\"}\n".
	        "[y/N] ";
          chomp($set_client_root_passwd=<STDIN>);
	}
	SWITCH: for ($set_client_root_passwd) {
	  /^y$|^yes$/i && do {
            $set_client_root_passwd="yes";
	    # we set 2 different passwords to make while loop works.
	    $client_root_passwd_1="init1";
	    $client_root_passwd_2="init2";
	    while ($client_root_passwd_1 ne $client_root_passwd_2 || ($client_root_passwd_1 eq "" && $client_root_passwd_2 eq "" )) {
                 print "$lang_deploy{\"whats_client_root_passwd\"}\n";
		 # turn off echo
                 system "LC_ALL=C stty -echo";
                 chomp($client_root_passwd_1=<STDIN>);
		 # turn on echo
                 system "LC_ALL=C stty echo";
                 print "$lang_deploy{\"retype_root_passwd\"}\n";
                 system "LC_ALL=C stty -echo";
                 chomp($client_root_passwd_2=<STDIN>);
                 system "LC_ALL=C stty echo";
	      if ($client_root_passwd_1 ne $client_root_passwd_2) {
		  print colored ("$lang_deploy{\"sorry_passwd_not_match\"}\n", "$color_warn");
	      }elsif ($client_root_passwd_1 eq "" && $client_root_passwd_2 eq "" ){
		  print colored ("$lang_deploy{\"sorry_passwd_can_not_empty\"}\n", "$color_warn");
	      }
	    }
	    $client_root_passwd=$client_root_passwd_1;
            last SWITCH;
	  };
          /.*/ && do {
            $set_client_root_passwd="no";
            print "$lang_deploy{\"ok_let_continue\"}\n";
            last SWITCH;
          };
	}

	# Ask if user want to set the pxelinux password of clients
        print "$delimiter{\"dash_line\"}\n".
              "$lang_deploy{\"set_client_pxelinux_passwd\"}\n".
	      "[y/N] ";
        chomp($set_client_pxelinux_passwd=<STDIN>);
	SWITCH: for ($set_client_pxelinux_passwd) {
	  /^y$|^yes$/i && do {
            $set_client_pxelinux_passwd="yes";
	    # we set 2 different passwords to make while loop works.
	    $client_pxelinux_passwd_1="pxeinit1";
	    $client_pxelinux_passwd_2="pxeinit2";
	    while ($client_pxelinux_passwd_1 ne $client_pxelinux_passwd_2 || ($client_pxelinux_passwd_1 eq "" && $client_pxelinux_passwd_2 eq "" )) {
                 print "$lang_deploy{\"whats_client_pxelinux_passwd\"}\n";
		 # turn off echo
                 system "LC_ALL=C stty -echo";
                 chomp($client_pxelinux_passwd_1=<STDIN>);
		 # turn on echo
                 system "LC_ALL=C stty echo";
                 print "$lang_deploy{\"retype_root_passwd\"}\n";
                 system "LC_ALL=C stty -echo";
                 chomp($client_pxelinux_passwd_2=<STDIN>);
                 system "LC_ALL=C stty echo";
	      if ($client_pxelinux_passwd_1 ne $client_pxelinux_passwd_2) {
		  print colored ("$lang_deploy{\"sorry_passwd_not_match\"}\n", "$color_warn");
	      }elsif ($client_pxelinux_passwd_1 eq "" && $client_pxelinux_passwd_2 eq "" ){
		  print colored ("$lang_deploy{\"sorry_passwd_can_not_empty\"}\n", "$color_warn");
	      }
	    }
	    $client_pxelinux_passwd=$client_pxelinux_passwd_1;
            last SWITCH;
	  };
	  /.*/ && do {
            $set_client_pxelinux_passwd="no";
            print "$lang_deploy{\"ok_let_continue\"}\n";
            last SWITCH;
          };
        }

	# Ask if user want to set the boot prompt for clients
	if ( $set_client_pxelinux_passwd eq "no" ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"set_client_system_select\"}\n".
	        "[Y/n] ";
          chomp($set_client_system_select=<STDIN>);
	  SWITCH: for ($set_client_system_select) {
	    /^n$|^no$/i && do {
              $set_client_system_select="no";
	      last SWITCH;
	    };
	    /.*/ && do {
              $set_client_system_select="yes";
	      while ($client_system_boot_timeout eq "") {
                   print "$lang_deploy{\"whats_client_system_boot_timeout\"}\n".
                         "[$DEFAULT_CLIENT_SYSTEM_BOOT_TIMEOUT] ";
                   chomp($client_system_boot_timeout_=<STDIN>);
	        if ( "$client_system_boot_timeout_" =~ /[^0-9]/ ) {
	  	  print colored ("$lang_deploy{\"sorry_timeout_must_be_number\"}\n", "$color_warn");
	        } else {
	            # if empty, use default timeout
                    if ($client_system_boot_timeout_ eq "") {
                      $client_system_boot_timeout_="$DEFAULT_CLIENT_SYSTEM_BOOT_TIMEOUT";
                    }
                    $client_system_boot_timeout="$client_system_boot_timeout_";
	        }
	      }
              print "$lang_deploy{\"ok_let_continue\"}\n";
              print "$delimiter{\"dash_line\"}\n";
	      last SWITCH;
            };
          }
        }

	# Ask if user want to use graphic pxe boot menu for clients
	# When serial console is found in pxelinux config file, force to set
	# $use_graphic_pxelinux_menu=no
	# When CLIENT_INIT is chosen as text mode, default to use txt PXE menu
        my $SERIAL_CONSOLE=`LC_ALL=C grep -Ewi "^serial" $pxecfg_pd/pxelinux.cfg/default 2>/dev/null`;
	if ( $SERIAL_CONSOLE ){
	  print "Serial console parameters are found in $pxecfg_pd/pxelinux.cfg/default. Force to use text PXELINUX menu, no graphic background.\n";
	  $use_graphic_pxelinux_menu="no"
	}
        if ( "$CLIENT_INIT" eq "text"){
	  $graphic_pxelinux_menu_default="no";
	  $graphic_pxelinux_menu_prompt="y/N";
	}else{
	  $graphic_pxelinux_menu_default="yes";
	  $graphic_pxelinux_menu_prompt="Y/n";
	}
	if ( ! $use_graphic_pxelinux_menu ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"use_graphic_pxelinux_menu\"}\n".
	         colored ("$lang_deploy{\"note_for_use_graphic_pxelinux_menu\"}\n", "$color_warn").
	        "[$graphic_pxelinux_menu_prompt] ";
          chomp($use_graphic_pxelinux_menu=<STDIN>);
	  if ( ! $use_graphic_pxelinux_menu ) { $use_graphic_pxelinux_menu=$graphic_pxelinux_menu_default }
	  SWITCH: for ($use_graphic_pxelinux_menu) {
	    /^n$|^no$/i && do {
	      print "Use text PXE Linux menu for the client.\n";
              $use_graphic_pxelinux_menu="no";
	      last SWITCH;
	    };
	    /.*/ && do {
	      print "Use graphic PXE Linux menu for the client.\n";
              $use_graphic_pxelinux_menu="yes";
	      last SWITCH;
            };
          }
        }
        print "$delimiter{\"dash_line\"}\n";

	# If Debian, ask if user want to set group plugdev and audio open
	# to all users
        if (-f "/etc/debian_version") {
	  if ( ! $set_DBN_client_audio_plugdev ) {
            print "$delimiter{\"dash_line\"}\n".
                  "$lang_deploy{\"set_DBN_client_audio_plugdev_etc_open_to_all\"}\n".
	          "[Y/n] ";
            chomp($set_DBN_client_audio_plugdev=<STDIN>);
	  }
	  SWITCH: for ($set_DBN_client_audio_plugdev) {
	    /^n$|^no$/i && do {
              $set_DBN_client_audio_plugdev="no";
	      last SWITCH;
	    };
	    /.*/ && do {
              $set_DBN_client_audio_plugdev="yes";
              print "$lang_deploy{\"ok_let_continue\"}\n";
              print "$delimiter{\"dash_line\"}\n";
	      last SWITCH;
            };
          }
        }

        # Ask if user want to set the public IP for clients
	if ( ! $set_client_alias_IP ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"set_client_alias_IP\"}\n".
                "[y/N] ";
          chomp($set_client_alias_IP=<STDIN>);
	}
        SWITCH: for ($set_client_alias_IP) {
            /^y$|^yes$/i && do {
                $set_client_public_ip_opt="yes";
                last SWITCH;
            };
            /.*/ && do {
                $set_client_public_ip_opt="no";
                last SWITCH;
            };
        }

	# Ask if user want to open the thin-client mode
	if ( ! $open_thin_client_option ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"open_thin_client_option\"}\n".
	        "[y/N] ";
          chomp($open_thin_client_option=<STDIN>);
	}
	SWITCH: for ($open_thin_client_option) {
	  /^y$|^yes$/i && do {
            $open_thin_client_option="yes";
	    last SWITCH;
	  };
	  /.*/ && do {
            $open_thin_client_option="no";
            print "$lang_deploy{\"ok_let_continue\"}\n";
            print "$delimiter{\"dash_line\"}\n";
	    last SWITCH;
	  };
        }

	# Ask if user want to turn DRBL server as a NAT server
	if ( ! $drbl_server_as_NAT_server ) {
          print "$delimiter{\"dash_line\"}\n".
                "$lang_deploy{\"drbl_server_as_NAT_server\"}\n".
	        "[Y/n] ";
          chomp($drbl_server_as_NAT_server=<STDIN>);
	}
	SWITCH: for ($drbl_server_as_NAT_server) {
	  /^n$|^no$/i && do {
            $drbl_server_as_NAT_server="no";
  	    print colored ("$lang_deploy{\"drbl_server_is_NOT_NAT_server\"}\n", "$color_warn");
	    last SWITCH;
	  };
	  /.*/ && do {
            $drbl_server_as_NAT_server="yes";
            print "$lang_deploy{\"ok_let_continue\"}\n";
            print "$delimiter{\"dash_line\"}\n";
	    last SWITCH;
	  };
        }

	# Ask if user want to purge client files if they exist
        $client_exist_flag=system("LC_ALL=C ls -d /tftpboot/nodes/* >/dev/null 2>&1") / 256;
        if ($client_exist_flag eq 0) {
	   # old clients exist
	   if ( ! $keep_client ) {
             print "$delimiter{\"dash_line\"}\n".
                   "$lang_deploy{\"keep_client_setting_question\"}\n".
	           "[Y/n] ";
             chomp($keep_client=<STDIN>);
           }
	   SWITCH: for ($keep_client) {
	     /^n$|^no$/i && do {
               $purge_client="yes";
               print "$lang_deploy{\"remove_client_setting\"}\n".
                     "$delimiter{\"star_line\"}\n";
	       last SWITCH;
	     };
	     /.*/ && do {
               $purge_client="no";
               print "$lang_deploy{\"keep_client_setting\"}\n".
                     "$delimiter{\"star_line\"}\n";
	       last SWITCH;
             };
           }
        }else{
	   # old clients do NOT exist, so it's not necessary to clean old files
           $purge_client="no";
        }

	#
        print "$delimiter{\"star_line\"}\n";

# output the config file
  	print CONFIG_FILE <<END_CFG;
#Setup for general
[general]
domain=$dnsdomain_sys
nisdomain=$nisdomain_sys
localswapfile=$localswapfile
client_init=$CLIENT_INIT
login_gdm_opt=$LOGIN_GDM_OPT
timed_login_time=$TIMED_LOGIN_TIME
maxswapsize=$maxswapsize
ocs_img_repo_dir=$ocs_img_repo_dir
total_client_no=$total_client_no
create_account=$create_account
account_passwd_length=$ACCOUNT_PASSWD_LENGTH_DEFAULT
hostname=$client_hostname_prefix
purge_client=$purge_client
client_autologin_passwd=$client_autologin_passwd
client_root_passwd=$client_root_passwd
client_pxelinux_passwd=$client_pxelinux_passwd
set_client_system_select=$set_client_system_select
use_graphic_pxelinux_menu=$use_graphic_pxelinux_menu
set_DBN_client_audio_plugdev=$set_DBN_client_audio_plugdev
open_thin_client_option=$open_thin_client_option
client_system_boot_timeout=$client_system_boot_timeout
language=$language
set_client_public_ip_opt=$set_client_public_ip_opt
config_file=$DRBLPUSH_CONF
collect_mac=$collect_mac
run_drbl_ocs_live_prep=$run_drbl_ocs_live_prep
drbl_ocs_live_server=$drbl_ocs_live_server
clonezilla_mode=$clonezilla_mode
live_client_branch=$live_client_branch
live_client_cpu_mode=$live_client_cpu_mode
drbl_mode=$drbl_mode
drbl_server_as_NAT_server=$drbl_server_as_NAT_server
add_start_drbl_services_after_cfg=$add_start_drbl_services_after_cfg
continue_with_one_port=$continue_with_one_port

END_CFG


        for($i=0;$i<=$#ethernet_sys;$i++) {
          my $ethx=$ethernet_sys[$i];
          if ( ! $MAC_file[$i] ){
	    # output the range format
  	    print CONFIG_FILE <<END_CFG;
#Setup for $ethx
[$ethx]
interface=$ethx
range=$range_start[$i]-$range_end[$i]
END_CFG
  	  }else{
 	    # output the MAC format
  	    print CONFIG_FILE <<END_CFG;
#Setup for $ethx
[$ethx]
interface=$ethx
mac=$MAC_file[$i]
ip_start=$range_start[$i]
END_CFG
	  }
	  # Put gateway if only one ethernet port is available, i.e. No NAT on this server.
	  if ( $#ethernet_list == 0 ) {  # Only one port
            my $gateway;
	    chomp($gateway=`LANG=C PATH=$PATH:/sbin/:/usr/sbin route -n | awk '/^0.0.0.0/ {print \$2}'`);
  	    print CONFIG_FILE <<END_CFG;
gateway=$gateway
END_CFG
	  }
	  # Append a space line
  	  print CONFIG_FILE <<END_CFG;

END_CFG
	}

        close(CONFIG_FILE);
	# set mode for more secure
	system("LC_ALL=C chmod 600 $DRBLPUSH_CONF");

}#end of interactive_mode

# subroutine to read file, parse them as parameters
# in: config_file
# out: hash of hash reference
sub read_config {

  my %HoH = ();
  my $KoH="general";
  my $key="",$value="";

  open(CONFIG,$_[0]) or die "Can NOT find file \"$_[0]\"! \nPlease check your config file!\n";
  while(<CONFIG>) {
    if($_=~/^#.*/) {
      # ignore comment
      #print "ignore $_\n";
    }
    elsif($_=~/\[.*\]/) {
      # has key
      chop;
      my $key_ = $_;
      # skip the comments
      $key_ =~ s/#.*//;
      # delete the spaces
      $key_ =~ s/ //g;
      $KoH=substr($key_,1,length($key_)-2);
    }
    else {
      # hash value
      chop;
      if( 0 == length($_) ) { next; }
      ($key,$value)=split(/=/);
      # Turn all the key to uppercase
      $key=uc($key);
      # skip the comments
      $value =~ s/#.*//;
      # delete the spaces
      $value =~ s/ //g;
      #print "KoH=$KoH, key=$key, value=$value\n";
      $HoH{ $KoH }{ $key }= $value;
    }
  }
  close(CONFIG);

  return( \%HoH );
}

sub drbl_server_parse {
# Part 1,
# get enough information, setup the DRBL server
#
  my $DNS_sys="/etc/resolv.conf";
  my $rHoH = read_config($_[0]);

  my $nameserver=$rHoH->{"general"}{"NAMESERVER"};
  my $domain=$rHoH->{"general"}{"DOMAIN"};
  my $nisdomain=$rHoH->{"general"}{"NISDOMAIN"};
  my $nfsserver_default=$rHoH->{"general"}{"NFSSERVER_DEFAULT"};
  my $localswapfile=$rHoH->{"general"}{"LOCALSWAPFILE"};
  my $CLIENT_INIT=$rHoH->{"general"}{"CLIENT_INIT"};
  my $maxswapsize=$rHoH->{"general"}{"MAXSWAPSIZE"};
  my $ocs_img_repo_dir=$rHoH->{"general"}{"OCS_IMG_REPO_DIR"};
  my $purge_client=$rHoH->{"general"}{"PURGE_CLIENT"};
  my $language=$rHoH->{"general"}{"LANGUAGE"};
  my $set_client_system_select=$rHoH->{"general"}{"SET_CLIENT_SYSTEM_SELECT"};
  my $use_graphic_pxelinux_menu=$rHoH->{"general"}{"USE_GRAPHIC_PXELINUX_MENU"};
  my $set_DBN_client_audio_plugdev=$rHoH->{"general"}{"SET_DBN_CLIENT_AUDIO_PLUGDEV"};
  my $open_thin_client_option=$rHoH->{"general"}{"OPEN_THIN_CLIENT_OPTION"};
  my $client_system_boot_timeout=$rHoH->{"general"}{"CLIENT_SYSTEM_BOOT_TIMEOUT"};
  my $set_client_public_ip_opt=$rHoH->{"general"}{"SET_CLIENT_PUBLIC_IP_OPT"};
  my $config_file=$rHoH->{"general"}{"CONFIG_FILE"};
  my $collect_mac=$rHoH->{"general"}{"COLLECT_MAC"};
  my $client_root_passwd=$rHoH->{"general"}{"CLIENT_ROOT_PASSWD"};
  my $client_pxelinux_passwd=$rHoH->{"general"}{"CLIENT_PXELINUX_PASSWD"};
  my $clonezilla_mode=$rHoH->{"general"}{"CLONEZILLA_MODE"};
  my $run_drbl_ocs_live_prep=$rHoH->{"general"}{"RUN_DRBL_OCS_LIVE_PREP"};
  my $drbl_ocs_live_server=$rHoH->{"general"}{"DRBL_OCS_LIVE_SERVER"};
  my $live_client_branch=$rHoH->{"general"}{"LIVE_CLIENT_BRANCH"};
  my $live_client_cpu_mode=$rHoH->{"general"}{"LIVE_CLIENT_CPU_MODE"};
  my $drbl_mode=$rHoH->{"general"}{"DRBL_MODE"};
  my $drbl_server_as_NAT_server=$rHoH->{"general"}{"DRBL_SERVER_AS_NAT_SERVER"};
  # Note! We do not write and read $sh_debug and $verbose_opt to and from config file, since they are runtime parameter

  # for login GDM
  my $login_gdm_opt=$rHoH->{"general"}{"LOGIN_GDM_OPT"};
  my $timed_login_time=$rHoH->{"general"}{"TIMED_LOGIN_TIME"};

  # for auto login or timed login account
  my $create_account=$rHoH->{"general"}{"CREATE_ACCOUNT"};
  my $account_prefix=$rHoH->{"general"}{"ACCOUNT_PREFIX"};
  my $account_passwd_length=$rHoH->{"general"}{"ACCOUNT_PASSWD_LENGTH"};
  my $total_client_no=$rHoH->{"general"}{"TOTAL_CLIENT_NO"};
  my $passwd_length=$rHoH->{"general"}{"ACCOUNT_PASSWD_LENGTH"};
  my $hostname_prefix=$rHoH->{"general"}{"HOSTNAME"};
  my $client_autologin_passwd=$rHoH->{"general"}{"CLIENT_AUTOLOGIN_PASSWD"};
  my $add_start_drbl_services_after_cfg=$rHoH->{"general"}{"ADD_START_DRBL_SERVICES_AFTER_CFG"};
  my $continue_with_one_port=$rHoH->{"general"}{"CONTINUE_WITH_ONE_PORT"};

  print "The GDM login option: $login_gdm_opt\n" if $verbosity >=2;
  print "timed_login_time: $timed_login_time\n" if $verbosity >=2;
  print "account_prefix: $account_prefix\n" if $verbosity >=2;
  print "total_client_no: $total_client_no\n" if $verbosity >=2;
  print "passwd_length: $passwd_length\n" if $verbosity >=2;
  print "maxswapsize in system is $maxswapsize\n" if $verbosity >= 2;
  print "ocs_img_repo_dir in system is $ocs_img_repo_dir\n" if $verbosity >= 2;
  print "Hostname_prefix from config file: \"$hostname_prefix\".\n" if $verbosity >= 2;

  # Try to get setting from system also
  chomp(my $nameserver_sys=`drbl-get-dnsserver`);
  print "nameserver in system is $nameserver_sys\n" if $verbosity >= 2;

  # get some setting in this server so that if some parameters are not set,
  # we can use the one in this system.
  chomp($dnsdomain_sys=`dnsdomainname`);
  chomp($nisdomain_sys=`nisdomainname`);
  print "DNSDOMAIN in system is $dnsdomain_sys\n" if $verbosity >= 2;
  print "NISDOMAIN in system is $nisdomain_sys\n" if $verbosity >= 2;

  # set nameserver, domain, nisdomain, the priority: use the config file first, if unset, then use the value in system
  if ( ! $nameserver ) {
   $nameserver = $nameserver_sys;
   print "* nameserver is not set in config file, \nthe one \"$nameserver\" got from system will be used.\n" if $verbosity >= 2;
  }
  if ( ! $nisdomain ) {
   $nisdomain = $nisdomain_sys;
   print "* nisdomain is not set in config file, \nthe one \"$nisdomain\" got from system will be used.\n" if $verbosity >= 2;
  }
  if ( ! $domain ) {
   $domain = $dnsdomain_sys;
   print "* dnsdomain is not set in config file, \nthe one got \"$domain\" from system will be used.\n" if $verbosity >= 2;
  }

  # check if the values are set in config file or system, just in case
  if ( ! $nameserver ) {
     print "Error! NAMESERVER is unset!\n";
     print "Please set it in config file \"$_[0]\" or $DNS_sys.\n";
     exit;
  }

  if ( ! $nisdomain ) {
     print "Error! NISDOMAIN is unset!\n";
     print "Please set it in config file \"$_[0]\" or system config file.\n";
     exit;
  }
  if ( ! $domain ) {
     print "Error! DOMAIN unset!\n";
     print "Please set it in config file \"$_[0]\" or system config file.\n";
     exit;
  }

  if ("$mode" eq "load_config_file") {
    # check public IP setting
    if ("$set_client_public_ip_opt" eq "yes" && ! -f "$drbl_syscfg/$public_ip_list") {
        print "$delimiter{\"star_line\"}\n".
              colored ("Unable to find the $drbl_syscfg/$public_ip_list; If you want to create the $drbl_syscfg/$public_ip_list, you must run \"drblpush\" in interactive mode (with -i option)!\n", "$color_warn").
              "$lang_deploy{\"press_enter_to_continue\"}";
              chomp($line=<STDIN>);
        print "$delimiter{\"dash_line\"}\n";
    }
    # check MAC address files
    if ("$collect_mac" eq "yes" ){ check_MAC_file("$drbl_syscfg","macadr-"); }
  }

  #
  if ($localswapfile eq "y" || $localswapfile eq "Y" || $localswapfile eq "yes" || $localswapfile eq "YES") {
      $mkswapfile="mkswapfile";
  }else{
      $mkswapfile="";
  }

  if ( "$login_gdm_opt" eq "timed_login" && ! $timed_login_time ) {
     print "You set config to timed login GDM, but there is no set time!\n".
           "We will set the time as $TIMED_GDM_TIME_DEFAULT seconds.\n";
  }

  # detect kernel in server support udp over NFS or tcp over NFS (tcp is the default seting one for DRBL environment)
  # try to get if the kernel running the server supports NFS over TCP, if not, ust NFS over UDP
  $nfsd_tcp_rlt=system("#!/bin/bash; . $DRBL_SCRIPT_PATH/sbin/drbl-functions; check_kernel_nfsd_tcp_config");
  if ($nfsd_tcp_rlt == 256) {
  	# set the protocol as udp
          $nfs_protocol="udp";
  }else{
  	# set the protocol as tcp
          $nfs_protocol="tcp";
  }
  $nfs_protocol_uc=uc $nfs_protocol;
  print "$lang_deploy{\"server_kernel_nfsd_support\"} ".
        colored ("NFS over $nfs_protocol_uc", "$color_warn").
        "!\n".
        colored ("$lang_deploy{\"change_kernel_notes\"}\n", "$color_warn").
        "$lang_deploy{\"press_enter_to_continue\"}";
        chomp($line=<STDIN>);
  print "$delimiter{\"dash_line\"}\n";

  #
  my $nameserver_=$nameserver;
  $nameserver_=~ s/\,/ /g;

  # generate dhcpd.conf, hosts, $main_sh...

  $main_sh="drbl_deploy.sh";
  # delete the old files
  unlink ($main_sh) if -f $main_sh;
  unlink (dhcpd.conf) if -f dhcpd.conf;
  unlink (nfsserver_all) if -f nfsserver_all;
  unlink (yp.conf) if -f yp.conf;
  unlink ($hosts_list) if -f $hosts_list;
  unlink ($CLIENT_IP_HOSTNAME_LIST) if -f $CLIENT_IP_HOSTNAME_LIST;
  unlink ($public_ip_list) if -f $public_ip_list;

  # open the config files for DRBL server
  open(DHCPD_OUT,">dhcpd.conf") or die "Can NOT write file \"dhcpd.conf\" \n";
  open(NETGROUP_OUT,">netgroup") or die "Can NOT write file \"netgroup\"! \n";
  open(DISKLESS_OUT,">$main_sh") or die "Can NOT write file \"$main_sh\" \n";
  open(NFSSERVER_OUT,">nfsserver_all") or die "Can NOT write file \"nfsserver_all\" \n";
  open(YPCONF_SERVER,">yp.conf") or die "Can NOT write file \"yp.conf\" \n";
  open(HOSTS_LIST_OUT,">$hosts_list") or die "Can NOT write file \"$hosts_list\" \n";
  open(CLIENT_HOST_IP_LIST_OUT,">$CLIENT_IP_HOSTNAME_LIST") or die "Can NOT write file \"$CLIENT_IP_HOSTNAME_LIST\" \n";
  open(SWAPCONF_OUT,">mkswapfile") or die "Can NOT write file \"mkswapfile\" \n";
  open(GLOBAL_SETTING,">drbl_deploy.conf") or die "Can NOT write file \"drbl_deploy.conf\" \n";

  ## get the etherboot zpxe filenames
  #print "Searching installed Etherboot files for dhcpd.conf... ";
  #chomp(my $etherboot_zpxe=`$query_pkglist_cmd drbl-etherboot | grep -E "eb-.*-etherboot-pci.zpxe\$" | xargs basename`);
  #chomp(my $sis900_zpxe=`$query_pkglist_cmd drbl-etherboot | grep -E "sis900.zpxe\$" | xargs basename`);
  #print "done! \n";
  my $pxe_file;
  if (-e "$pxecfg_pd/lpxelinux.0"){
    $pxe_file="lpxelinux.0";
  }else{
    $pxe_file="pxelinux.0";
  }

  print "$delimiter{\"star_line\"}\n";

  # some general option in dhcpd.conf, hosts, $main_sh
  print DHCPD_OUT <<EOF;
# Generated by DRBL.
# Do NOT modify this file unless you know what you are doing!

default-lease-time			$DHCPD_DEFAULT_LEASE_TIME;
max-lease-time				$DHCPD_MAX_LEASE_TIME;
option subnet-mask			255.255.255.0;
option domain-name-servers  		$nameserver;
option domain-name			"$domain";
ddns-update-style                       none;
server-name 				drbl;

allow booting;
allow bootp;

# For Raspberry Pi
# Ref: https://www.raspberrypi.org/forums/viewtopic.php?t=209247
#      https://tools.ietf.org/html/rfc2132
option vendor-specific-info    code 43 = string;            # Server - RFC 2132, 8.4
option param-request-list      code 55 = string;            # Client - RFC 2132, 9.8
option vendor-class-identifier code 60 = string;            # Client - RFC 2132, 9.13
option rpi-tftp-server         code 66 = text;              # Server - RFC 2132, 9.4

# Ref: Dynamic Host Configuration Protocol (DHCP) Options for the
#      Intel Preboot eXecution Environment (PXE)
#      https://tools.ietf.org/html/rfc4578
#      https://tools.ietf.org/html/rfc5071
option arch code 93 = unsigned integer 16;                  # Client - RFC 4578, 2.1
option space pxelinux;                                     
#option pxelinux.magic      code 208 = string;              # Server - RFC 5071, 3.2
#option pxelinux.configfile code 209 = text;                # Server - RFC 5071, 4.2
#option pxelinux.pathprefix code 210 = text;                # Server - RFC 5071, 5.2
#option pxelinux.reboottime code 211 = unsigned integer 32; # Server - RFC 5071, 6.2

site-option-space "pxelinux";

if exists dhcp-parameter-request-list {
    # Always send the PXELINUX options (specified in hexadecimal, i.e.: 208=0xd0, 209=0xd1, etc.)
    option dhcp-parameter-request-list = concat(option dhcp-parameter-request-list,d0,d1,d2,d3);
}
# Ref:
# http://www.syslinux.org/wiki/index.php/PXELINUX
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=720589
# //NOTE// From DRBL 2.15, bootia32.efi and bootx64.efi could be the one from
# (1) syslinux (scripts/sbin/prepare-files-for-PXE-client)
# or
# (2) grub (drbl-gen-grub-efi-nb)
# Ref: http://ipxe.org/cfg/platform. Thanks to Danny Russ for providing this.
if option arch = 00:00 {
    # Intel x86PC or
    # Raspberry Pi, which should not declare itself as an Intel x86PC.
    # Ref: https://kiljan.org/2019/11/16/arch-linux-arm-network-boot-on-raspberry-pi-4/
    # We will overwrite it later in the class "raspberrypi".
    filename "lpxelinux.0";
} else if option arch = 00:06 {
    # EFI IA32
    filename "bootia32.efi";
} else if option arch = 00:07 or
          option arch = 00:09 {
    # EFI BC or EFI x86-64 
    filename "bootx64.efi";
} else if option arch = 00:0a {
    # armv7 (arm 32 bit)
    filename "bootarm.efi";
} else if option arch = 00:0b or
          option arch = 00:16 {
    # aarch64 (arm 64 bit)
    # Rockpro64 (https://www.pine64.org/rockpro64) uses 00:16
    filename "bootaa64.efi";
} else {
    # Default to Intel x86PC
    filename "lpxelinux.0";
}

class "raspberrypi" {
  # Raspberry Pi, which should not declare itself as an Intel x86PC.
  # However, we still can identify it by some methods.
  # Ref: https://kiljan.org/2019/11/16/arch-linux-arm-network-boot-on-raspberry-pi-4/
  match if (
    (
          # Parameter list from Pi 3B ROM and old bootcode.bin
          binary-to-ascii(10,8,",",option param-request-list) =
            "43,60,67,128,129,130,131,132,133,134,135,66"
          # Parameter list from Pi 3B+ ROM and newer bootcode.bin
       or binary-to-ascii(10,8,",",option param-request-list) =
            "43,60,67,128,129,130,131,132,133,134,135,66,1,3"
          # Parameter list from Pi 4B EEPROM boot code (2019-10-16)
       or binary-to-ascii(10,8,",",option param-request-list) =
            "1,3,43,60,66,67,128,129,130,131,132,133,134,135"
    ) 
    and option vendor-class-identifier = "PXEClient:Arch:00000:UNDI:002001"
    and option arch = 00:00    # Architecture: Intel x86PC
    and (
         substring(hardware,1,3) = b8:27:eb # Pi Foundation OUI listing
      or substring(hardware,1,3) = dc:a6:32 # Raspberry Pi Trading Ltd OUI listing
    )
  );
  # There are extra 3 spaces in the end for vendor-specific-info, due to a bug in bootrom for Raspberry Pi <= 3
  # No need for Raspberry Pi 4, but it is OK to have that.
  # Ref: https://www.raspberrypi.org/documentation/hardware/raspberrypi/bootmodes/net.md
  option vendor-specific-info "Raspberry Pi Boot   ";
  # bootcode.bin is not used on the Raspberry Pi 4, because it has been replaced by boot code in the onboard EEPROM.
  # Older model needs that.
  # Ref: https://www.raspberrypi.org/documentation/configuration/boot_folder.md
  filename "bootcode.bin";
}

## Uncomment the following "if block" when you have some buggy PXE NIC card (such as annoying sis900 NIC). Remember to modify the MAC vendor prefix and restart dhcpd service!!!
## This is a workround for some network card with BAD PXE code in firmware.
## It will only affect those clients with MAC vendor prefix you assigned.
## Ref: http://syslinux.zytor.com/archives/2005-August/005640.html

#if substring (option vendor-class-identifier, 0, 3) = "PXE" {
#     # **************************************************************
#     # ***MODIFY*** the MAC vendor prefix of client network card here.
#     # **************************************************************
#     # For annoying sis900 network card, maybe it is 00:07:95, 00:0C:6E...
#     if substring (hardware, 1, 3) = 00:0C:6E {
#         # sis900.zpxe is specially for sis900 NIC, you can download it from
#         # http://rom-o-matic.net/etherboot/etherboot-5.4.4/contrib/rom-o-matic
#         filename = "sis900.zpxe";
#     }
#}

# Uncomment the following to get the debug/verbose messages in system log. The messages like the following will be shown:
# PXEClient:Arch:00009:UNDI:003016
# Begin of log command
#log ( info, vendor-class-identifier ) ;
# End of log command

# Uncomment the following to get the debug/verbose messages in system log. The messages like the following will be shown:
# Client 0:c:29:1d:9a:d1 with arch 0:7 requests 1:2:3:4:5:6:c:d:f:11:12:16:17:1c:28:29:2a:2b:32:33:36:3a:3b:3c:42:43:61:80:81:82:83:84:85:86:87 - PXEClient:Arch:00007:UNDI:003016 - no dhcp-client-id
# Client 0:c:29:e5:a4:2 with arch 0:0 requests 1:2:3:5:6:b:c:d:f:10:11:12:2b:36:3c:43:80:81:82:83:84:85:86:87 - PXEClient:Arch:00000:UNDI:002001 - no dhcp-client-id
# Client 0:c:29:3b:34:fb with arch 0:0 requests 1:3:6:c:f:1c:28:29:2a - DRBLClient - no dhcp-client-id
# Begin of log command
#log(info, concat("Client ",
#        binary-to-ascii(16, 8, ":", substring(hardware, 1, 6)),
#        " with arch ",
#        binary-to-ascii(16, 8, ":", option arch),
#        " requests ",
#        binary-to-ascii(16, 8, ":", option dhcp-parameter-request-list),
#        " - ",
#        pick-first-value(option vendor-class-identifier, "no vendor-id"),
#        " - ",
#        pick-first-value(option dhcp-client-identifier, "no dhcp-client-id"))
#   );
# End of log command

# This class 'DRBL-Client' defines 3 kind of clients: PXE, Etherboot (1st stage) or DRBL client (2nd stage, i.e. in network initrd/initramfs (mkpxeinitrd-net)) to lease IP address.  This will only affect 'range' statement only, not the 'host' statement.
# Note! The following line(s) in the pool statement: 'allow members of "DRBL-Client";' is/are commented to disable this mechanism by default.
# If you do want to use this mechanism, uncomment all 'allow members of "DRBL-Client";', then only PXE, etherboot and DRBL client can lease IP address from this DHCP service.
# ///NOTE/// In summary, two cases you can turn on this mechanism:
# (1) This DRBL server is not used as a clonezilla server.
# (2) This DRBL server is used as a Clonezilla server, with the following conditions:
#     (a) 'range' statement is used in this DRBL service.
#     (b) There is an existing DHCP service which can provide IP address leases to the restored OS (either GNU/inux or MS Windows) in the client. Otherwise if you uncomment 'allow members of "DRBL-Client";', restored OS won't be able to lease IP address.

# The DRBL client class: PXE, Etherboot or DRBL client
class "DRBL-Client" {
  match if
  (substring(option vendor-class-identifier, 0, 9) = "PXEClient") or
  (substring(option vendor-class-identifier, 0, 9) = "Etherboot") or
  (substring(option vendor-class-identifier, 0, 10) = "DRBLClient") ;
}

# If you want to use special port for DHCP service, edit here:
# For more info, ref: http://drbl.sourceforge.net/faq/index.php#path=./2_System&entry=37_coexist_with_existing_dhcp.faq
# local-port 1067;
# remote-port 1068;

EOF

  # set the config file for mkswapfile
  print SWAPCONF_OUT "maxswapsize=$maxswapsize\n";

  print CLIENT_HOST_IP_LIST_OUT "# Created by DRBL (drblpush), begin\n";

  print NETGROUP_OUT "# Added by DRBL, begin\n";
  print NETGROUP_OUT "nodes ";

# write the nis client config file for server, i.e. ypbind will also run in
# DRBL server, so that user can use yppasswd to change his passwd in server.
# The yp server is the DRBL server, too, so we use localhost.
  print YPCONF_SERVER <<YPCONF_SERVER_EOF;
domain $nisdomain server localhost
YPCONF_SERVER_EOF

# output the global setting for drbl_deploy
  print GLOBAL_SETTING <<GLOBAL_EOF;
##################################
# drbl_deploy global setting
# File automatically created by drblpush.
# It is better not to manually modify this file.
##################################
config_file="$config_file"
purge_client="$purge_client"
client_root_passwd="$client_root_passwd"
client_pxelinux_passwd="$client_pxelinux_passwd"
language="$language"
set_client_system_select="$set_client_system_select"
use_graphic_pxelinux_menu="$use_graphic_pxelinux_menu"
set_DBN_client_audio_plugdev="$set_DBN_client_audio_plugdev"
open_thin_client_option="$open_thin_client_option"
client_system_boot_timeout="$client_system_boot_timeout"
collect_mac=$collect_mac
total_client_no=$total_client_no
nfs_protocol="$nfs_protocol"
client_init="$CLIENT_INIT"
mkswapfile="$mkswapfile"
ocs_img_repo_dir="$ocs_img_repo_dir"
nfsserver_default="$nfsserver_default"
nameserver="$nameserver"
nameserver_="$nameserver_"
domain="$domain"
nisdomain="$nisdomain"
public_ip_list="$public_ip_list"
login_gdm_opt="$login_gdm_opt"
client_autologin_passwd="$client_autologin_passwd"
timed_login_time="$TIMED_LOGIN_TIME"
run_drbl_ocs_live_prep="$run_drbl_ocs_live_prep"
drbl_ocs_live_server="$drbl_ocs_live_server"
clonezilla_mode="$clonezilla_mode"
live_client_branch="$live_client_branch"
live_client_cpu_mode="$live_client_cpu_mode"
drbl_mode="$drbl_mode"
sh_debug="$sh_debug"
verbose_opt="$verbose_opt"
CLIENT_IP_HOSTNAME_LIST="$CLIENT_IP_HOSTNAME_LIST"
drbl_server_as_NAT_server="$drbl_server_as_NAT_server"
add_start_drbl_services_after_cfg="$add_start_drbl_services_after_cfg"
continue_with_one_port="$continue_with_one_port"
use_proxy_dhcp="$use_proxy_dhcp"
##################################
# End of global setting
##################################

GLOBAL_EOF

close(GLOBAL_EOF);
system("chmod 600 drbl_deploy.conf");
system("mkdir -p $drbl_syscfg; cp -f drbl_deploy.conf $drbl_syscfg/");

  print DISKLESS_OUT <<EOF;
#!/bin/bash $sh_debug
# **********************************************************************
# File automatically created by drblpush,
# better not to modify this file manually.
# "drblpush" is written by K. L. Huang, klhaung _at_ gmail com,
# especially for Debian, then modified to use with Redhat by
# Steven Shiau, steven _at_ clonezilla org.
# Ceasar Sun, ceasar _at_ nchc org tw
# **********************************************************************

# Load DRBL setting and functions
DRBL_SCRIPT_PATH="\${DRBL_SCRIPT_PATH:-/usr/share/drbl/}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl_deploy.conf

# Get distribution ID and release number.
[ -e /etc/lsb-release ] && . /etc/lsb-release

# get the l10n message
if [ -f "$DRBL_SCRIPT_PATH/lang/bash/$language" ] ; then
 . $DRBL_SCRIPT_PATH/lang/bash/$language
else
   echo "Not such language option!!!"
   exit 1
fi

# store the orig LC_ALL, then set it as C
LC_ALL_org=\$LC_ALL
export LC_ALL=C

EOF

print DISKLESS_OUT q{
# Decide the sysv init service control program is update-rc.d or insserv in Debian or Ubuntu. The output variable is "$dbn_ubn_serv_control_prog".
if [ -e /etc/debian_version ]; then
  get_debian_ubuntu_init_serv_control_prog

  # Jul/30/2015 Besides, due to this issue on Debian/Ubuntu:
  # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=793760
  # we disabled efi_netboot_1st_in_nvram
  # otherwise for Clonezilla SE the uEFI clients will always enter Clonezilla
  # mode after finishing the previous Clonezilla job. One day when Debian/Ubuntu
  # applies the patch, we will enable it.
  # //NOTE// Sep/19/2015 We have used grub embedded preconfig way in drbl-gen-grub-efi-nb
  # to solve this issue:
  # http://lists.gnu.org/archive/html/help-grub/2015-09/msg00035.html
  # Therefore disable this.
  # LC_ALL=C perl -pi -e 's/^efi_netboot_1st_in_nvram=.*/efi_netboot_1st_in_nvram="no" # Disabled when running drblpush/g' /etc/drbl/drbl-ocs.conf
fi

# Create the prerun/postrun dirs if they do not exist
mkdir -p $DRBLPUSH_PRERUN_DIR $DRBLPUSH_POSTRUN_DIR
# pre run
if [ -n "$(unalias ls 2>/dev/null; ls $DRBLPUSH_PRERUN_DIR/ 2>/dev/null)" ]; then
  echo "Some files are found in $DRBLPUSH_PRERUN_DIR. Run them first..."
  drbl-run-parts $DRBLPUSH_PRERUN_DIR
fi
# check if the space is enough to setup DRBL
echo -n "Checking the necessary disk space... "
# When none full drbl mode AND none full clonezilla mode, only 1 client. Otherwise we will generate all the clients.
if [ "$clonezilla_mode" != "full_clonezilla_mode" -a \
     "$drbl_mode" != "full_drbl_mode" ]; then
  total_client_no_for_checking="1"
else
  total_client_no_for_checking="$total_client_no"
fi
space_check=$(check_drbl_setup_space -n $total_client_no_for_checking)
rc=$?
if [ "$rc" -gt 0 ]; then
  total_avail_space=$(echo $space_check | awk '{print $1}')
  drbl_need_space=$(echo $space_check | awk '{print $2}')
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_total_avail_space: $total_avail_space (MB)"
  echo "$msg_necessary_space_setup_drbl: $drbl_need_space (MB)"
  echo "$msg_total_client_no: $total_client_no"
  echo "$msg_system_maybe_not_enough_space"
  echo "$msg_press_ctrl_c_stop!"
  echo "$msg_press_enter_to_continue"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  read
fi
echo "done!"

# copy the config files to $drbl_syscfg...
echo -n "Copying the config file to $drbl_syscfg... "
mkdir -m 700 -p $drbl_syscfg
cp -f $config_file $drbl_syscfg/
[ -f $public_ip_list ] && cp -f $public_ip_list $drbl_syscfg/
echo "done!"

# Do some checks...
if [ "$(dirname $drbl_common_root)" = "/" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "You can NOT assign the drbl_common_root as / in drbl.conf!!!"
  echo "Program terminated!!!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

# varlib_NOT_2_be_copied_2_each_client and varcache_2_be_copied_2_common_root are loaded from drbl.conf
# varlib_NOT_2_be_copied_2_each_client -> varlib_opts_common_to_each is processed in
# sbin/drbl-gen-client-files

# "$DISTRIB_ID" is from /etc/lsb-release
if [ "$DISTRIB_ID" = "Ubuntu" ]; then
  case "$DISTRIB_RELEASE" in
   "10.10")
      # Weird Buggy Ubuntu 10.10 (Maverick)... The /var/lib/nfs/{sm,sm.bak} are not owned by statd in 1:1.2.2-1ubuntu1. It's owned by root. No idea how it happens, it's not always. Anyway force to add this for Ubuntu 10.10.
      if [ "$(LC_ALL=C stat -c %U /var/lib/nfs/sm)" != "statd" ]; then
        chown -R statd /var/lib/nfs/{sm,sm.bak}
      fi
    ;;
   "18.04")
      # systemd-logind's IP sandbox breaks nss-nis and suchlike #7074 
      # Thanks to Robert Arkiletian for reporting this in drbl mailing list.
      # Ref: https://sourceforge.net/p/drbl/mailman/message/36319119/
      #      https://github.com/systemd/systemd/issues/7074
      perl -pi -e "s/^IPAddressDeny=any/#IPAddressDeny=any # commented by DRBL/g" /lib/systemd/system/systemd-logind.service
      perl -pi -e "s/^IPAddressDeny=any/#IPAddressDeny=any # commented by DRBL/g" /lib/systemd/system/systemd-udevd.service
    ;;
  esac
fi
# Ubuntu >= 20.10 has a hook file zz-dhclient causing server booting to lease IP address. We do not need that.
if grep -Ewq "^cp -a /usr/lib/initramfs-tools/etc/dhcp/.*" /usr/share/initramfs-tools/hooks/zz-dhclient 2>/dev/null; then
  echo "Found /usr/share/initramfs-tools/hooks/zz-dhclient. Comment it to avoid running dhclient in initramfs."
  perl -pi -e "s|^(cp -a /usr/lib/initramfs-tools/etc/dhcp/.*)|# \$1 # commented by DRBL|" /usr/share/initramfs-tools/hooks/zz-dhclient
  update-initramfs -u
fi

# If purge_client = no, which means we will NOT overwrite the old files.
# we had better to add "-u" for rsync, and we assign keep_old_files_flag=yes
if [ "$purge_client" = "no" ]; then
  RSYNC_OPT_EXTRA="-u"
  keep_old_files_flag="yes"
else
  RSYNC_OPT_EXTRA=""
  keep_old_files_flag="no"
fi

# check if drbl is installed or not, which is necessary
if ! rpm -q --quiet drbl &>/dev/null && ! chk_deb_installed drbl &>/dev/null; then
  echo "You did NOT install drbl!!! Program terminated!"
  exit 1
fi

# backup the original setting files in DRBL server
[ -f $DHCPDCONF_DIR/dhcpd.conf ] && mv -f $DHCPDCONF_DIR/dhcpd.conf $DHCPDCONF_DIR/dhcpd.conf.orig
[ -f /etc/netgroup ] && mv -f /etc/netgroup /etc/netgroup.drblsave
[ -f /var/yp/securenets ] && mv -f /var/yp/securenets /var/yp/securenets.drblsave
[ -f /etc/ypserv.securenets ] && mv -f /etc/ypserv.securenets /etc/ypserv.securenets.drblsave
# We do not want the old ethers, this will cause lag in network. Thanks to Dave Haakenhout <Dave.Haakenhout _at_ nccw nl>
[ -e /etc/ethers ] && mv -f /etc/ethers /etc/ethers.orig

# Backup the old clients-of-$nfsserver.txt
for i in $drbl_syscfg/clients-of-*.txt; do
  if [ -f "$i" ]; then
    mv -f $i ${i}.drblsave
  fi
done

# copy some config files (dhcpd.conf, yp.conf...) created
# in the drblpush DRBL server.

cp -f dhcpd.conf $DHCPDCONF_DIR/
# Generate the dnsmasq config file
if [ "$use_proxy_dhcp" = "yes" ]; then
  # Only create dnsmasq.conf when use_proxy_dhcp is set as yes.
  gen_dnsmasq_cfg $dnsmasq_cfg
fi

cp -f mkswapfile $SYSCONF_PATH/mkswapfile

for icfg in yp.conf netgroup; do
  cp -f $icfg /etc/
done

# put the temp hostname to /etc/drbl
cp -f $CLIENT_IP_HOSTNAME_LIST $IP_HOST_TABLE

# put clients-of-*.txt to /etc/drbl/
cp -f clients-of-*.txt $drbl_syscfg/

# create /etc/hosts based on drblpush.conf and dhcpd.conf, so must be after dhcpd.conf is copied to system.
drbl-etc-hosts

echo -n "Cleaning the stale files of the diskless nodes if they exist... "
# clean the config or setting files in $drbl_common_root/etc/diskless-image
# and /tftpboot/nodes/*/etc/diskless-image.
# This action is important, otherwise the stalled files will always exist.
find $drbl_common_root/etc/diskless-image $drblroot/*/etc/diskless-image -name "config" -exec rm -f {} \; &> /dev/null
find $drbl_common_root $drblroot -name "$public_ip_list" -exec rm -f {} \; &> /dev/null
echo "done!"

#
# backup the old MAC address files if the collect MAC is on
if [ "$collect_mac" = "yes" ]; then
  echo -n "Backuping the old MAC address files... "
  now=$(date +%F-%k-%M)
  find $drbl_syscfg -name "macadr-*.txt" -exec mv {} {}.saved_$now \;
  echo "done!"
fi

# Part 2,
# generate file system for clients, like what is done in Debian diskless-newimage
#

# Setting
echo "$msg_delimiter_star_line"
# get the distribution name and type: OS_Version and OS_type
check_distribution_name
echo "$msg_delimiter_star_line"
if [ -z "$OS_Version" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "$msg_not_determine_OS"
  echo "$msg_is_not_supported"
  echo "$msg_press_ctrl_c_stop!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  read
  exit 1
fi
echo "The version number for your GNU/Linux: $OS_Version"

# First, common root files
[ ! -d /tftpboot ] && mkdir /tftpboot

# When user changes ocsroot, we need to modify drbl.conf (note: This must be after $drbl_common_root//$ocsroot is created)
# If this script is rerun, maybe clonezilla.lock exists.
if [ -f "$ocs_lock_dir/clonezilla.lock" ]; then
   echo "Your system is already in clonezilla mode... we will stop it when running drblpush so it will not in a mess."
   drbl-ocs -l 0 stop
else
   # prepare a dir for ocs lock file
   mkdir -p $ocs_lock_dir
fi
# We need the clonezilla image dir ($ocs_img_repo_dir for sever, and $drbl_common_root/$ocs_img_repo_dir for client to use it as a mount point) if it does not exist, and we will write it into drbl.conf so that the later script will read that.
mkdir -p $ocs_img_repo_dir $drbl_common_root/$ocs_img_repo_dir
# Create Clonezilla log dir
mkdir -p $ocs_log_dir

# ocsroot is supposed to be /home/partimag if untouched, if it is assigned to different one, we have to modify drbl.conf
# strip the last / if it exists ( avoid this does not match "/home/partimag" <-> "/home/partimag/" , actually they are same)
ocsroot="$(LC_ALL=C echo $ocsroot | sed -e "s|/[[:space:]]*$||g")"
ocs_img_repo_dir="$(LC_ALL=C echo $ocs_img_repo_dir | sed -e "s|/[[:space:]]*$||g")"
if [ "$ocs_img_repo_dir" != "$ocsroot" ]; then
  sub_cmd="s|^[[:space:]]*ocsroot=.*|ocsroot=\"$ocs_img_repo_dir\" # Modified by drblpush|g"
  perl -pi -e "$sub_cmd" /etc/drbl/drbl.conf
fi

case "$purge_client" in
   [yY][eE][sS])
      echo -n "Completely cleaning old common root files if they exist... "
      # Clean the stalled files...
      [ -d $drbl_common_root/etc ] && rm -rf $drbl_common_root/etc
      [ -d $drbl_common_root/var ] && rm -rf $drbl_common_root/var
      echo "done !"

      echo -n "Completely cleaning old nodes if they exist... "
      # Clean old node files
      for iclient in $drblroot/[0-9]*; do
        [ -d "$iclient" -a -n "$(echo "$iclient" | grep -E "[0-9]")" ] && rm -rf $iclient
      done

      echo "done !"
      ;;
   *)
      echo "Keeping the old common root files if they exist... "
      echo "Keeping old nodes if they exist... "
      ;;
esac

echo -n "Creating common root files... This might take several minutes..."
echo -n "."
# diskless_root_dir_1 are those necessary dir for mount point (from drbl.conf).
# From Debian Sid 201108, the /run (tmpfs) is required. Therefore if it can be found on server, append it. Ref: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=620157
[ -d "/run" ] && diskless_root_dir_1="$diskless_root_dir_1 run"
# $diskless_root_dir_ro_user_add $diskless_root_dir_rw_user_add are user assigned dirs in drbl.conf
for d in $diskless_root_dir_1 $diskless_root_dir_ro_user_add $diskless_root_dir_rw_user_add; do
   mkdir -p $drbl_common_root/$d
done
# diskless_root_dir_2 are those necessary dir for mount point (from drbl.conf), too. These dirs depend on distribution, so we will test it before create it.
for d in $diskless_root_dir_2; do
   [ -d "/$d" ] && mkdir -p $drbl_common_root/$d
done

# locale en_US.UTF-8 will be the default locale for clonezilla dialog in console. Therefore we have to create that.
gen_locale_if_not_found en_US en_US.UTF-8

# 1/7/2006, since B2D does not have /media, but it will create and use that
# once you plug the usb devices, so now we mkdir media for DRBL B2D client
echo -n "."
if [ -e /etc/b2d-release ]; then
  mkdir -p $drbl_common_root/media
fi

echo -n "."
# copy some rc files to root home directory
for ir in .bashrc .bash_profile .profile .viminfo; do
  [ -f /root/$ir ] && rsync -a $RSYNC_OPT_EXTRA /root/$ir $drbl_common_root/root/
done

# create the console so that client can output message when entering init. This is especially for Debian.
echo -n "."
# force to clean the old ones
for i in console null; do
  [ -c $drbl_common_root/dev/$i ] && rm -f $drbl_common_root/dev/$i
done
mknod -m 600 $drbl_common_root/dev/console c 5 1
mknod -m 666 $drbl_common_root/dev/null c 1 3

#
echo -n "."
# copy /sbin, /bin to node_root
# For FC17, since /sbin is linked to /usr/sbin, we have to create /sbin, /bin first
mkdir -p $drbl_common_root/usr/{sbin,bin}

# Note!!! For rsync, do NOT to append "/" in the /sbin, .i.e. NO /sbin/
rsync -a $RSYNC_OPT_EXTRA /usr/sbin/* $drbl_common_root/usr/sbin/
# Because Ubuntu 15.04 hides insserv in /usr/lib/insserv/insserv due to switch
# to systemd. However, it's important for us to enable sysvinit service (some
# services are not systemdlized yet, e.g. nis in Ubuntu 15.04). Therefore force
# to put it in $drbl_common_root/sbin/
# Variable DESTDIR is required for copy_exec_drbl use
export DESTDIR="$drbl_common_root"
[ -e "/usr/lib/insserv/insserv" ] && copy_exec_drbl /usr/lib/insserv/insserv /sbin/

#
echo -n "."
rsync -a $RSYNC_OPT_EXTRA /usr/bin/* $drbl_common_root/usr/bin/
# We need awk and cut in init.drbl.
# For RH-like, awk and cut are in /bin, however, in Debian, they are in /usr/bin, which is not mounted when trying to get IP address of NFS server in running init.drbl. So we have to copy them.
# Note!!! In Debian, we need the gawk, not awk, so we already installed gawk
# in drblsrv, and it will replace awk as /etc/alternatives/awk -> /usr/bin/gawk
# But maybe it is better to cp gawk -> awk ?
must_prog_for_init_drbl="cut gawk"
for imust in $must_prog_for_init_drbl; do
  [ -e "$drbl_common_root/bin/$imust" ] && rm -f $drbl_common_root/bin/$imust
  if [ -e "/usr/bin/$imust" ]; then
     #echo "Copying $imust from /usr/bin/ to $drbl_common_root/bin/..."
     cp -af --dereference /usr/bin/$imust $drbl_common_root/bin/
  else
     [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
     echo "FATAL error!!! $imust is not found in /usr/bin!!! Client will NOT be able to boot or run correctly!!!"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
done
# link gawk as awk for clients.
(cd $drbl_common_root/usr/bin/; ln -fs gawk awk)
# For gawk_3.1.8+dfsg-0.1 on Debian sid (2011/07/30), it requires /usr/lib/*.so*# $ ldd /usr/bin/gawk
# linux-gate.so.1 =>  (0xb76eb000)
# libsigsegv.so.2 => /usr/lib/libsigsegv.so.2 (0xb76d7000)
# libdl.so.2 => /lib/i386-linux-gnu/i686/cmov/libdl.so.2 (0xb76d3000)
# libm.so.6 => /lib/i386-linux-gnu/i686/cmov/libm.so.6 (0xb76ac000)
# libc.so.6 => /lib/i386-linux-gnu/i686/cmov/libc.so.6 (0xb7552000)
# /lib/ld-linux.so.2 (0xb76ec000)
#
export DESTDIR="$drbl_common_root"
[ -e "$(LC_ALL=C command -v gawk)" ] && copy_exec_drbl "$(LC_ALL=C command -v gawk)" /usr/bin/

echo -n "."
# Creat a file $drbl_common_root/usr/sbin/fsck.nfs to let rc.sysinit use
# "fsck.nfs" always successfully
echo "#!/bin/bash
# dummy fsck.nfs file that always returns success.
# Created by drblpush to let rc.sysinit use fsck.nfs always successfully
exit 0" > $drbl_common_root/usr/sbin/fsck.nfs
chmod 755 $drbl_common_root/usr/sbin/fsck.nfs

echo -n "."

for id in lib lib64 bin sbin; do
  mkdir -p $drbl_common_root/usr/$id
  if [ -L "/$id" ]; then
    if [ ! -L "$drbl_common_root/$id" ]; then
      (cd $drbl_common_root; ln -fs usr/$id $id) 
    fi
  fi
done
# Steven todo, make sure it is right ?
# $drbl_common_root/lib/security is important for PAM, if we remove/update it,
# clients have to reboot, otherwise user can not login in the client.
# So it is better to keep $drbl_common_root/lib/security/ without updating.
# if [ -d $drbl_common_root/lib/security ]; then
#   rsync -a $RSYNC_OPT_EXTRA --exclude=modules/ --exclude=security/ /lib $drbl_common_root/
# else
#   rsync -a $RSYNC_OPT_EXTRA --exclude=modules/ /lib $drbl_common_root/
# fi
# 2006/6/1 Just sync it, otherwise /lib/security will not be updated, some files will be missing.
# 2012/9/26 For FC17 since /lib is linked as /usr/lib, we have to copy files, not the linked dir.
lib_opts_common_to_common=""
for iv in $lib_NOT_2_be_copied_2_common_root; do
  lib_opts_common_to_common="$lib_opts_common_to_common --exclude=$iv/ "
done
rsync -a $lib_opts_common_to_common /usr/lib/* $drbl_common_root/usr/lib/

# For x86_64
# For FC3 or later: /lib64 is a directory, not /lib32, only dir /lib
# For Ubuntu breezy amd64: /lib64 is a symbolic to /lib, /lib32 is a directory
for d in lib lib32 libx32 lib64; do
 if [ -L "/$d" ]; then
   rsync -a /$d/* $drbl_common_root/usr/$d/
 fi
done

echo " done!"

# Copy or update the kernel for client if necessary...
echo "Update the kernel for client if necessary... "
update-drbl-client-kernel-from-server $verbose_opt $RSYNC_OPT_EXTRA

# copy /etc to template node
# etc_exclude_dirs is loaded from drbl.conf
etc_rsync_opt=""
for ietc in $etc_exclude_dirs; do
  etc_rsync_opt="$etc_rsync_opt --exclude=$ietc"
done
echo "Copying the directory /etc/ to clients common root $drbl_common_root..."
rsync -a $etc_rsync_opt $RSYNC_OPT_EXTRA /etc $drbl_common_root

# For Ubuntu 6.10 (edgy), there is no /etc/inittab, but upstart still respect
# inittab. We will create one for client, but for edgy+1 or later, maybe not respect /etc/inittab, then we have to follow upstart in the future.
#if [ ! -f /etc/inittab ]; then
#  cat <<-INIT_END > $drbl_common_root/etc/inittab
## inittab created by DRBL.
## This file is created to be backward compatible with Ubuntu Dapper/Breezy and Debian Sarge/Etch. Although Ubuntu Edgy now uses upstart instead of sysvinit, it still respect /etc/inittab, but in Edgy+1 or later, maybe it will not respect.
#
## The default runlevel.
#id:2:initdefault:
#INIT_END
#fi
#

# clean the ssh key, so that client will create its own.
key_file="ssh_host_dsa_key ssh_host_dsa_key.pub ssh_host_key ssh_host_key.pub ssh_host_rsa_key ssh_host_rsa_key.pub"
for ik in $key_file; do
  if diff /etc/ssh/$ik $drbl_common_root/etc/ssh/$ik &>/dev/null; then
     echo -n "Cleaning the ssh key file $ik copied from server... "
     rm -f $drbl_common_root/etc/ssh/$ik
     echo "done!"
  fi
done

# comment /etc/hosts.allow and /etc/hosts.deny in drbl client
for ik in hosts.deny hosts.allow; do
  echo -n "Commenting the TCPwrapper related file $drbl_common_root/etc/$ik copied from server... "
  perl -pi -e 's/^([^#][[:print:]]+)$/# $1 #  commented by DRBL/g' $drbl_common_root/etc/$ik
  echo "done!"
done

# clean the mtab in $drbl_common_root copied from server
rm -f $drbl_common_root/etc/mtab*

# clean the netplan file copied from server
rm -f $drbl_common_root/etc/netplan/*.yaml

# For Debian udev, if $drbl_common_root/etc/udev/rules.d/z25_persistent-net.rules exists, remove it. Since it contains the network MAC address from drbl server, and we should let client automatically create that.
if [ -n "$(unalias ls 2>/dev/null; ls $drbl_common_root/etc/udev/rules.d/*persistent-net.rules 2>/dev/null)" ]; then
  rm -f $drbl_common_root/etc/udev/rules.d/*persistent-net.rules
fi

# make sure the hostname of server in 127.0.0.1 in /etc/hosts
# is not copied to clients.
# like
#-----------------------------------------------------------
#127.0.0.1               rh9 localhost.localdomain localhost
#-----------------------------------------------------------
# if it is copied to client, client will have some problem to connect to server
# such as yppasswd will complain the yppasswdd is NOT running on "rh9".
HOSTNAME_SRV=`/usr/bin/hostname`
if [ -n "$(grep $HOSTNAME_SRV $drbl_common_root/etc/hosts |grep 127.0.0.1)" ]; then
 perl -p -i -e "s/127.0.0.1.*/127.0.0.1		localhost.localdomain localhost/g" $drbl_common_root/etc/hosts
fi

# create mkswapfile to $drbl_common_root/etc/init.d/
# This must before service to add
cp -f $drbl_setup_path/files/misc/{mkswapfile,drblthincli,arm-wol} $drbl_common_root/etc/init.d/
# ocs-run is a script to start clone for clonezilla, it only will be put in
# client's rc1.d when clonezilla save/restart start.
cp -f $drbl_setup_path/files/ocs/ocs-run $drbl_common_root/etc/init.d/
# For Debian, there is no gdm-safe-restart script, we just copy it from drbl
# package. We need gdm-safe-restart for terminal mode setup.
[ ! -x /usr/sbin/gdm-safe-restart ] && cp -f $drbl_setup_path/files/misc/gdm-safe-restart /usr/sbin/gdm-safe-restart
chown root:root $drbl_common_root/etc/init.d/{mkswapfile,drblthincli,arm-wol}
# Put systemd services for {mkswapfile,drblthincli,arm-wol}
if is_systemd_init; then
  cp -f $drbl_setup_path/files/misc/systemd/{mkswapfile.service,drblthincli.service,arm-wol.service} $drbl_common_root/lib/systemd/system/
  if [ -e /etc/debian_version ]; then
    # Write the override file for remote-fs-pre of systemd due to nfs-utils
    # in Debian does not ship native systemd unit files.
    # Ref: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=768006
    mkdir -p $drbl_common_root/lib/systemd/system/nfs-common.service.d/
    cp -f $drbl_setup_path/files/misc/systemd/remote-fs-pre.conf $drbl_common_root/lib/systemd/system/nfs-common.service.d/
    if [ ! -e /etc/systemd/system/tmp.mount -a \
         ! -e /lib/systemd/system/tmp.mount -a \
           -e /usr/share/systemd/tmp.mount ]; then
      # Debian systemd 220 disabled tmp.mount, and it might cause our diskless client umount /tmp in amd64. We have to enable it.
      # Ref: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=779902
      if [ -e "$drbl_common_root/etc/default/tmpfs" ]; then
        perl -pi -e "s/[#]RAMTMP=.*/RAMTMP=yes/g" $drbl_common_root/etc/default/tmpfs
      fi
      cp -a /usr/share/systemd/tmp.mount $drbl_common_root/lib/systemd/system/tmp.mount
      # Manuall link the tmp.mount since systemctl fails to run in chroot.
      mkdir -p $drbl_common_root/etc/systemd/system/local-fs.target.wants/
      ln -fs /lib/systemd/system/tmp.mount $drbl_common_root/etc/systemd/system/local-fs.target.wants/tmp.mount
    fi
  fi
fi

# For MDK/Debian/SuSE, we put the one we wrote "firstboot.XXX.drbl" to
# common root /etc/init.d as firstboot.
# There is already firstboot comes with RH/FC/CentOS.
# We do NOT use the firstboot comes with yast2-firstboot in SuSE.
if [ "$OS_type" != "RH" ]; then
  if [ -f "$drbl_setup_path/files/${OS_type}/${OS_Version}/firstboot.${OS_Version}.drbl" ]; then
    cp -f $drbl_setup_path/files/${OS_type}/${OS_Version}/firstboot.${OS_Version}.drbl $drbl_common_root/etc/init.d/firstboot
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Warning! The fine-tune file ${drbl_setup_path}/files/${OS_type}/${OS_Version}/firstboot.${OS_Version}.drbl was not found. Using ${drbl_setup_path}/files/${OS_type}/firstboot.default-${OS_type}.drbl as /etc/init.d/firstboot for DRBL clients!"
    echo "This may cause some problems to DRBL clients!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    cp -f $drbl_setup_path/files/${OS_type}/firstboot.default-${OS_type}.drbl $drbl_common_root/etc/init.d/firstboot
  fi
fi

# modify some bootup script or setting (System V is easier to do here.. all scripts are separated.)
if [ -e /etc/debian_version ]; then
  # Debian
  # For genuine Debian Sarge
  if [ -e $drbl_common_root/etc/init.d/umountfs ]; then
    perl -pi -e 's/(^[[:space:]]*umount -ttmpfs.*)/#$1 # Modified by DRBL/g' $drbl_common_root/etc/init.d/umountfs
    perl -pi -e 's/(^[[:space:]]*umount -tnoproc)(,noprocfs.*)/$1,nonfs,notmpfs$2 # Modified by DRBL/g' $drbl_common_root/etc/init.d/umountfs
    # For genuine Debian Etch
    perl -pi -e 's/(^[[:space:]]*)(proc|procfs|linprocfs|devfs|sysfs|usbfs.*)/$1nfs|tmpfs|none|$2/g' $drbl_common_root/etc/init.d/umountfs
    # for B2D
    perl -pi -e 's/^[[:space:]]*umount \$FORCE -a -r.*/umount \$FORCE -tnoproc,nonfs,notmpfs,noprocfs,nodevfs,nosysfs,nousbfs,nousbdevfs,nodevpts -d -a -r # Modified by DRBL/g' $drbl_common_root/etc/init.d/umountfs
    # for Ubuntu Dapper
    # To avoid $DIR is noting.
    # Ref: https://lists.ubuntu.com/archives/ubuntu-users/2006-May/079378.html
    perl -pi -e 's|^([[:space:]]*)(umount -r -d \$DIRS*)|$1 [ -n "\$DIRS" ] && $2 # Modified by DRBL|g' $drbl_common_root/etc/init.d/umountfs
    # For Debian Squeeze, by default it uses parallel start service "startpar" (i.e. CONCURRENCY=makefile). We disable it in the client so that we won't have to modify the services. E.g. /etc/rc1.d/*ssh when running clonezilla SE job.
  fi
  if [ -e $drbl_common_root/etc/init.d/rc ]; then
    LC_ALL=C perl -pi -e "s|^CONCURRENCY=.*|CONCURRENCY=none # Mofified by DRBL|g" $drbl_common_root/etc/init.d/rc
    # Disable the lvm udevd, otherwise this rule file will be read-only in the client, and it will be auto-run during booting. Then the disk will be always busy. Clonezilla will fail to create partition table.
  fi
  disable_lvm2_udevd_rules $drbl_common_root

elif [ -e /etc/SuSE-release ]; then
  # For SuSE
  # SuSE is unique here, it uses parallel start service "startpar", we do not
  # want that, otherwise some services might fail due to NFS client does not
  # finish yet.
  echo -n "Turn off runlevel scripts in parallel in clients... "
  perl -pi -e "s/^[[:space:]]*[#]*[[:space:]]*RUN_PARALLEL=.*/RUN_PARALLEL=no/g" $drbl_common_root/etc/sysconfig/boot
  echo "done!"
  # modify some services
  # 1. etc/init.d/boot, use -o remount so it will not complain when booting.
  perl -pi -e 's/^([[:space:]]*mount -n -t proc)(.*)/$1 -o remount $2 # Modified by DRBL/g' $drbl_common_root/etc/init.d/boot
  perl -pi -e 's/^([[:space:]]*mount -n -t sysfs)(.*)/$1 -o remount $2 # Modified by DRBL/g' $drbl_common_root/etc/init.d/boot
  # 2. boot.udev, we have to turn on runlevel 1 so that clonezilla will be ok.
  perl -pi -e 's/^[[:space:]]*#+[[:space:]]*Default-Start:.*/# Default-Start:     B 1/g' $drbl_common_root/etc/init.d/boot.udev
  # 3. boot.localfs, we add -l when umount in "boot.udev stop" (called by reboot/halt)
  perl -pi -e 's/^([[:space:]]*umount) -avt (noproc,nonfs.*)/$1 -avtl nosysfs,$2 # Modified by DRBL/g' $drbl_common_root/etc/init.d/boot.localfs
  # 3. nfs client,
  # (a) For OpenSuSE 11.1, it seems if we do not restart dbus after NFS is run, something weird. E.g. When xdm start, an error:
  # Starting service gdm ** (gdm:2916): WARNING **: Couldn't connect to system bus: Failed to connect to socket /var/run/dbus/system_bus_socket: Connection refused startproc:  exit status of parent of /usr/sbin/gdm: 1 failed
  # Therefore we force to restart dbus after nfs dirs are mounted:
  perl -pi -e 's|^([[:space:]]*mount -at nfs.*)|$1; /etc/init.d/dbus restart # Modified by DRBL|g' $drbl_common_root/etc/init.d/nfs
  # (b) We do not want to recreate ld.so.cache, it is only provided
  # by DRBL server.
  # Note! recreate here will take a long time.
  # Note2: boot.ldconfig is run before nfs.
  # It will not include some remote NFS directory
  # (like /opt/kde/lib... /opt/gnome/lib...
  # we have to turn off boot.ldconfig in /etc/init.d/boot.d also.
  # Here we put "true" so that if there is only one command in the if/else block, the nfs start script won't fail.
  perl -pi -e 's|^([[:space:]]*#+)[[:space:]]*check if ld.so.cache needs to be refreshed.*|$1 DRBL comment this, we will not let boot.ldconfig run in DRBL client.|g' $drbl_common_root/etc/init.d/nfs
  perl -pi -e 's|/etc/init.d/(boot.ldconfig start.*)|true #$1|g' $drbl_common_root/etc/init.d/nfs
  rm -f $drbl_common_root/etc/init.d/boot.d/[SK][0-9][0-9]boot.ldconfig
fi

# Remove the unnecessary service,
# First, remove all the service
# Prepare the necessary env for chkconfig, update-rc.d or insserv
if [ -e /etc/debian_version ]; then
  # For Debian
  prepare_update_rc_d_env $drbl_common_root/
elif [ -e /etc/SuSE-release ]; then
  # For SuSE
  create_insserv_env $drbl_common_root/
else
  # For RH-like
  create_chkconfig_env $drbl_common_root/
fi
# Skip those do not support chkconfig, or actually, they are not services.
# reboot/halt are necessary for all dists.
# For FC17, getty@ is required.
service_to_be_kept="dualconf functions reboot halt killall single mandrake_consmap mandrake_everytime mandrake_firstime usb getty@"

# For normal service in init.d
isrv_list="$(cd $drbl_common_root/etc/init.d; ls *)"
# For systemd-like , E.g. FC17
if is_systemd_init; then
  isrv_list="$isrv_list $(find $drbl_common_root/lib/systemd/system -name "*.service" -type f -exec basename {} \;| sed -e "s/\.service$//g")"
fi

for isrv in $isrv_list ; do
  # Skip directory
  [ -d "$drbl_common_root/etc/init.d/$isrv" -o -d "$drbl_common_root/lib/systemd/system/$isrv.service" ] && continue
  # keep some services.
  [ -n "$(echo $service_to_be_kept | grep -w $isrv)" ] && continue
  if is_systemd_init; then
    # For systemd-like, E.g. FC17, Debian Jessie, Ubuntu 15.04
    echo "Deleting '$isrv' service in systemd-like environment ..."
    if [ -e "$drbl_common_root/etc/init.d/$isrv" ]; then
      if [ -x "$drbl_common_root/sbin/chkconfig" ]; then
        chroot $drbl_common_root/ /sbin/chkconfig --del $isrv
      elif [ -x "$drbl_common_root/sbin/insserv" ]; then
        chroot $drbl_common_root/ insserv -f -r $isrv &> /dev/null
      fi
      find $drbl_common_root/etc/rc*.d -regex ".*[SK][-0-9][0-9]$isrv" -exec rm -f {} \;
    fi
    if [ -e "$drbl_common_root/lib/systemd/system/${isrv}.service" ]; then
      find $drbl_common_root/etc/systemd/ -name "${isrv}.service" -exec rm -f {} \;
    fi
  elif [ -e /etc/debian_version ]; then
    # For Debian
    # We should keep the services in rcS.d, but "update-rc.d remove" does
    # not support this. It will also clean all the services in rcS.d.
    # So we will copy those services of rcS.d to client's common root
    # after this. NOTE! This can only be done after all updata-rc.d
    # finished. Otherwise it will affect the update-rc.d
    if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
      chroot $drbl_common_root/ insserv -f -r $isrv &> /dev/null
    else
      chroot $drbl_common_root/ /usr/sbin/update-rc.d -f $isrv remove &> /dev/null
    fi
  elif [ -e /etc/SuSE-release ]; then
    # For SuSE
    # There are a lot of boot.* services, we must exclude them also.
    # Special case: boot.udev, which only starts in boot, 2, 3, 5, but we need
    # it to start in 1 also. So we remove boot.udev here, then modify it, then
    # add it later.
    [ "$isrv" = "boot.udev" ] && chroot $drbl_common_root/ /sbin/insserv -f -r $isrv
    [ -n "$(echo $isrv | grep "^boot.*")" ] && continue

    [ "$isrv" = "Makefile" ] && continue
    [ "$isrv" = "README" ] && continue
    [ "$isrv" = "rc" ] && continue
    chroot $drbl_common_root/ /sbin/insserv -f -r $isrv
  else
    # For RH-like
    chroot $drbl_common_root/ /sbin/chkconfig --del $isrv
    # Maybe it will fail to delete the service, so try to delete brutely.
    # This happens in Mandriva 2007.0. Bugs report:
    # http://qa.mandriva.com/show_bug.cgi?id=24409
    # http://qa.mandriva.com/show_bug.cgi?id=23104
    # In Mandriva 2008.0, there is some special service start name "S-1", like:
    # ./rc.d/rc3.d/S-1nfs-common,  ./rc.d/rc3.d/S-1nfs-server
    # Therefore it's not "[SK][0-9][0-9]$i", it's "[SK][-0-9][0-9]$i" here.
    ( cd $drbl_common_root/etc
      find ./rc*.d -regex ".*[SK][-0-9][0-9]$isrv" -exec rm -f {} \;
    )
  fi
done

# Set journal.conf for FC 21 to solve bootup hanging, by Ceasar
# Ref: http://forums.gentoo.org/viewtopic-t-806432-view-previous.html?sid=206e0c04aa942972883135971a18c6ae
# Add into clients' /etc/systemd/journald.conf
# Storage=volatile
# SystemMaxUse=20M
# SystemMaxFileSize=20M

if [ -e "$drbl_common_root/etc/systemd/journald.conf" ]; then
  sed -i -e "/SystemMaxUse\=/d" -e "/SystemMaxFileSize\=/d" -e "/Storage\=/d" $drbl_common_root/etc/systemd/journald.conf
  echo "Storage=volatile" >> $drbl_common_root/etc/systemd/journald.conf
  echo "SystemMaxUse=20M" >> $drbl_common_root/etc/systemd/journald.conf
  echo "SystemMaxFileSize=20M" >> $drbl_common_root/etc/systemd/journald.conf
fi

# Get the gdm or kdm config filename
# get_gdm_kdm_conf_filename will also process lightdm/mdm. For Ubuntu 14.04, /etc/lightdm/lightdm.conf does not exist, and get_gdm_kdm_conf_filename will unzip the one "/usr/share/doc/lightdm/lightdm.conf.gz" and put it in /etc/lightdm/
get_gdm_kdm_conf_filename

if [ -z "$GDM_CFG" ]; then
  prepare_gdm_custom_conf
fi

# set gdm.conf for DRBL clients
if [ -f "$drbl_common_root/$GDM_CFG" -a "$set_drbl_gdmgreeter" = "yes" ]; then
  # force to use graphic greeting (gdmgreeter is available in sarge, not in woody. In woody, it is gdmlogin)
  # gdmgreeter: /usr/bin/gdmgreeter (sarge) or /usr/lib/gdm/gdmgreeter (breezy)
  # gnome 2.14: /usr/libexec/gdmgreeter
  GDM_GREETER="$($query_pkglist_cmd gdm 2>/dev/null | grep -E "\/gdmgreeter$")"
  if [ -n "$GDM_GREETER" ]; then
   # Set Greeter=$GDM_GREETER
   lines="$(get_block_line_in_gdm_kdm daemon $drbl_common_root/$GDM_CFG)"
   begin_line=$(echo $lines | awk -F" " '{print $1}')
   end_line=$(echo $lines | awk -F" " '{print $2}')
   chk_cmd="if ($begin_line..$end_line) {print}"
   if [ -n "$(perl -n -e "$chk_cmd" $drbl_common_root/$GDM_CFG | grep -i "^Greeter=")" ]; then
     sub_cmd="if ($begin_line..$end_line) {s|^Greeter=.*|Greeter=$GDM_GREETER|}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
   else
     # insert 1 blank line
     sub_cmd="if ($((end_line))..$((end_line))) {s|^(.*)$|\$1\n|gi}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
     # replace the one we want in the added blank line
     sub_cmd="if ($((end_line+1))..$((end_line+1))) {s|^$|Greeter=$GDM_GREETER|gi}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
   fi
   # Set GraphicalTheme=drbl-gdm
   lines="$(get_block_line_in_gdm_kdm greeter $drbl_common_root/$GDM_CFG)"
   begin_line=$(echo $lines | awk -F" " '{print $1}')
   end_line=$(echo $lines | awk -F" " '{print $2}')
   chk_cmd="if ($begin_line..$end_line) {print}"
   if [ -n "$(perl -n -e "$chk_cmd" $drbl_common_root/$GDM_CFG | grep -i "^GraphicalTheme=")" ]; then
     sub_cmd="if ($begin_line..$end_line) {s|^GraphicalTheme=.*|GraphicalTheme=drbl-gdm|}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
   else
     # insert 1 blank line
     sub_cmd="if ($((end_line))..$((end_line))) {s|^(.*)$|\$1\n|gi}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
     # replace the one we want in the added blank line
     sub_cmd="if ($((end_line+1))..$((end_line+1))) {s|^$|GraphicalTheme=drbl-gdm|gi}"
     perl -pi -e "$sub_cmd" $drbl_common_root/$GDM_CFG
   fi
  fi
fi

# 2nd, add the service which DRBL client need
client_services=""
# Add the necessary services:
# firstboot is always necessary. Even for MDK, there is no firstboot in /etc/init.d, we will add it which is provided by DRBL. It will control the run level
# via chkconfig (i.e. for rc3, although the service is added, but it will
# not run.
# Note by Steven Shiau on 2006/09/26, we put firstboot in the beginning
# (hence it's in front of the dm service of Mandriva), since in LSB based
# service, we need to put firstboot before dm, otherwise dm might run
# before firstboot.
client_services="$client_services firstboot"

# client_services_chklist is loaded in drbl.conf.

# check if the service listed exists
for iser in $client_services_chklist; do
   # For systemd, chcek /lib/systemd/system/*.service
   [ -e "/etc/init.d/$iser" -o -f "/lib/systemd/system/${iser}.service" ] && client_services="$client_services $iser"
done

# add the services only exist in DRBL client.
client_services="$client_services drblthincli $mkswapfile arm-wol"

# For some distribution, add special service if DRBL is configured to run
# some desktop application, such as iiimf, cups.

# add some special services for specific distribution
if [ -e /etc/debian_version ]; then
  # For Debian
  # The umountfs is already modified by drblpush
  client_services="$client_services sendsigs umountfs"
elif [ -e /etc/SuSE-release ]; then
  # For SuSE
  # Suse uses xdm to start kdm/gdm/xdm, they are all in the same service name.
  # We foced to use the modified boot.udev (it's on in runlevel 1,2,3,4,5
  # Note: "nfs" is server in RH, but it's client in SuSE. So we have to add it
  # separately for SuSE.
  client_services="$client_services nfs xdm boot.udev"
else
  # For RH-like
  # IIim in FC2, iiim in FC3, scim for MDK 10.1 (scim is not a service, so skip this). Try to find which one...
  for iinput in IIim iiim; do
     if [ -n "$(LC_ALL=C [ -x /sbin/chkconfig ] && chkconfig --list $iinput 2>/dev/null | awk '/5:on/ {print $7}')" -o -n "$(LC_ALL=C [ -x /sbin/chkconfig ] && chkconfig --list $iinput 2>/dev/null | awk '/3:on/ {print $5}')" ]; then
        client_services="$client_services $iinput"
     fi
  done
  # Due to this bug, we force to turn on gpm in FC4.
  # https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=158620
  case "$OS_Version" in
    FC[4-9]|FC1[01234])
       # To avoid this bug, shit!
       # https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=158620
       if [ -e "$drbl_common_root/etc/init.d/gpm" ]; then
         client_services="$client_services gpm"
         # modify the gpm so that it will start in rc1, clonezilla is run in rc1.d
         perl -pi -e "s/^# chkconfig: 2345 85 15/# chkconfig: 12345 17 83/g" $drbl_common_root/etc/init.d/gpm
       fi
       ;;
  esac
fi

# add the services specified by user
if [ -e "$drbl_syscfg/client-extra-service" ]; then
  . $drbl_syscfg/client-extra-service
  client_services="$client_services $service_extra_added"
fi

echo "The startup services for DRBL client are:"
# strip the leading space
[ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
echo $(echo $client_services | sed -e "s/^ //g")
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

# prepare the necessary env for chkconfig, update-rc.d or insserv
if [ -e /etc/debian_version ]; then
  # For Debian
  prepare_update_rc_d_env $drbl_common_root/
elif [ -e /etc/SuSE-release ]; then
  # For SuSE
  create_insserv_env $drbl_common_root/
else
  # For RH-like
  create_chkconfig_env $drbl_common_root/
fi
for i in $client_services; do
  if is_systemd_init; then
    # Systemd system
    echo "Enabling service $i..."
    case "$i" in
      ypbind)
        # remove ypserv
        sed -i -e "s/[[:space:]]*ypserv.service//" $drbl_common_root/lib/systemd/system/$i.service
        ;;
      dm)
        # TODO: start drblthincli before dm.
        true
        ;;
      netfs)
        # TODO
        true
        ;;
    esac
    if [ -e "$drbl_common_root/lib/systemd/system/$i.service" ]; then
      # systemctl can't work in chroot environment :`chroot $drbl_common_root/ /sbin/chkconfig --add $i`
      # Therefore manually link it:
      _systemctl_target=$(grep -e "^WantedBy=" $drbl_common_root/lib/systemd/system/$i.service | sed -e "s/WantedBy=//")
      if [ ! -z "$_systemctl_target" ]; then
        echo "to target: '$_systemctl_target'";
        for ti in $_systemctl_target; do
          ln -s -v /lib/systemd/system/$i.service $drbl_common_root/etc/systemd/system/$ti.wants/$i.service
        done
      else
        echo "Skip ...";
      fi
    fi
    # 2024/9/14 Comment this backup plan, since systemd service is enabled.
    # if [ -e "$drbl_common_root/etc/init.d/$i" ]; then
    #   if [ -x "$drbl_common_root/sbin/chkconfig" ]; then
    #     echo "Running: chroot $drbl_common_root/ /sbin/chkconfig --add $i"
    #     chroot $drbl_common_root/ /sbin/chkconfig --add $i
    #   elif [ -x "$drbl_common_root/usr/sbin/update-rc.d" ]; then
    #     echo "Running: chroot $drbl_common_root /usr/sbin/update-rc.d $i defaults"
    #     chroot $drbl_common_root /usr/sbin/update-rc.d $i defaults
    #     echo "Running: chroot $drbl_common_root /usr/sbin/update-rc.d $i enable"
    #     chroot $drbl_common_root /usr/sbin/update-rc.d $i enable
    #   elif [ -x "$drbl_common_root/sbin/insserv" ]; then
    #     # Use insserv for debian/ubuntu
    #     # Ubuntu >= 16.10, there is no insserv at all.
    #     # Add '-f' to fix adding nis service error in Xenial, by Ceasar
    #     echo "Running: chroot $drbl_common_root/ insserv -f $i &> /dev/null"
    #     chroot $drbl_common_root/ insserv -f $i &> /dev/null
    #   fi
    # fi
  elif [ -e /etc/debian_version ]; then
    if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
      # Use insserv
      chroot $drbl_common_root/ insserv $i &> /dev/null
    else
      # Use update-rc.d
      case "$i" in
        portmap)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 18 2 3 4 5 . start 32 0 6 . stop 32 1 . &> /dev/null
          ;;
        rpcbind)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 18 2 3 4 5 . start 32 0 6 . stop 32 1 . &> /dev/null
          ;;
        nis)
          # nis should be earlier than gdm (S13)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 12 2 3 4 5 . stop 12 0 1 6 . &> /dev/null
          ;;
        sendsigs)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 20 0 6 . &> /dev/null
          ;;
        umountfs)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 40 0 6 . &> /dev/null
          ;;
        mkswapfile)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 35 2 3 4 5 . stop 65 0 1 6 . &> /dev/null
          ;;
        firstboot)
          # chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 95 2 3 4 5 . stop 05 0 1 6 . &> /dev/null
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 95 S . &> /dev/null
          ;;
        drblthincli)
          # drblthincli must be before gdm/kdm
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 12 2 3 4 5 . stop 88 0 1 6 . &> /dev/null
          ;;
        nfs-common)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 21 2 3 4 5 . stop 79 0 1 6 . &> /dev/null
          ;;
        acpid)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 10 2 3 4 5 . stop 21 0 1 6 . &> /dev/null
          ;;
        acpi-support)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 99 2 3 4 5 . stop 20 0 1 6 . &> /dev/null
          ;;
        usplash)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 98 2 3 4 5 . stop 01 0 1 6 . &> /dev/null
          ;;
        arm-wol)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 99 2 3 4 5 . &> /dev/null
          ;;
        dbus)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 12 2 3 4 5 . &> /dev/null
          ;;
        hal)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i start 24 2 3 4 5 . &> /dev/null
          ;;
        *)
          chroot $drbl_common_root/ /usr/sbin/update-rc.d $i defaults &> /dev/null
          ;;
      esac
    fi
  elif [ -e /etc/SuSE-release ]; then
    # SuSE
    chroot $drbl_common_root/ /sbin/insserv -f $i
  else
    # RH-like
    # Note by Steven Shiau on 2006/9/26
    # Mandriva 2007 uses LSB service config and parallel init.
    # We have to modify some services
    case "$i" in
      ypbind)
        # remove ypserv
        perl -pi -e 's/^(#[[:space:]]*Should-Start: )(ypserv)(.*)/$1 $3/g' $drbl_common_root/etc/init.d/$i
        perl -pi -e 's/^(#[[:space:]]*Should-Stop: )(ypserv)(.*)/$1 $3/g' $drbl_common_root/etc/init.d/$i
        ;;
      dm)
        # We need drblthincli to run before dm, so when drblthincli is on, it
	# will start before dm.
        perl -pi -e 's/^#[[:space:]]*Required-Start:.*/# Required-Start: xfs firstboot netfs drblthincli/g' $drbl_common_root/etc/init.d/$i
        ;;
      netfs)
        # Mandriva 2009.0 or newer netfs will exit if /var/lock/subsys/network not existing.
	# It's: [ ! -f /var/lock/subsys/network -a ! -f /var/lock/subsys/NetworkManager ] && exit 0
        perl -pi -e 's|(^[[:space:]]*)(.*/var/lock/subsys/network.*)|$1#$2 # Modified by DRBL|g' $drbl_common_root/etc/init.d/$i
        ;;
    esac
    chroot $drbl_common_root/ /sbin/chkconfig --add $i
    # case "$i" in
    #   ypbind)
    #   # When using chkconfig --add ypbind, client do not put in rcx.d, since on
    #   # RH/FC it is:
    #   # chkconfig: - 27 73
    #   # Hence we use chkconfig ypbind to turn on it.
    #   # For Mandriva 2010.0, "chkconfig ypbind on" will also make ypbind on in rc7.d (although it's "# chkconfig: 345 17 83" in mandriva's /etc/init.d/ypbind, but since mandriva 2007 it has used LSB service config instead of honor the chkconfig tag), but it will fail when running graphic mode since rpcbind is not on in rc7.d. Here we can not force to turn on it.
    #   if [ -n "$(grep -E "^# chkconfig: - " $drbl_common_root/etc/init.d/$i)" ]; then
    #     # For RH/FC case
    #     chroot $drbl_common_root/ /sbin/chkconfig $i on
    #   fi
    # esac
    # 10/27/2012 Force to turn on the service. If only using "chkconfig --add", the service might not be in the "on" status. It will only make those services "on" on the server to be "on" on the client. Thanks to Odin Nøsen for reporting this.
    # Ref: http://sourceforge.net/mailarchive/forum.php?thread_name=CANCtYmUJYn5XNx6RS-sP9xVWqctjHYahn0egWY_Bxc-%2BTGnMiA%40mail.gmail.com&forum_name=drbl-user
    chroot $drbl_common_root/ /sbin/chkconfig $i on
  fi
done
# Deal with ocs-run service in systemd environment
#	1. create rescue.target and services files
#	2. make a link of rescue.service to ocsd-rescue.service
#	3. remove /etc/rc*.d/S*ocs-run to avoid ocs-run service competition
if is_systemd_init; then
  [ -e /etc/lsb-release ] && . /etc/lsb-release
  [ ! -d "$drbl_common_root/etc/systemd/system/rescue.target.wants" ] && mkdir "$drbl_common_root/etc/systemd/system/rescue.target.wants"
  cp -P $drbl_common_root/etc/systemd/system/multi-user.target.wants/* $drbl_common_root/etc/systemd/system/rescue.target.wants/
  if [ -d $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/systemd/system ]; then
    # For Ubuntu, first find its own one.
    cp $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/systemd/system/ocsd-*.service $drbl_common_root/etc/systemd/system/
  elif [ -d $drbl_setup_path/files/${OS_type}/${OS_Version}/systemd/system ]; then
    cp $drbl_setup_path/files/${OS_type}/${OS_Version}/systemd/system/ocsd-*.service $drbl_common_root/etc/systemd/system/
  else
    # Can not find fine-tune file, show warning, and use the most related one.
    OS_Version_Major="${OS_Version:0:3}"  # E.g. CO7.1.1503 -> CO7; DBN9.2 -> DBN9
    most_related_ver_d="$(LC_ALL=C find $drbl_setup_path/files/$OS_type/${OS_Version_Major}* -maxdepth 1 -type d -exec dirname {} \; 2>/dev/null | sort -V | uniq | tail -n 1)"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Warning! The fine-tune files in dir ${drbl_setup_path}/files/${OS_type}/${OS_Version}/systemd/system/ were not found. Using ocs-related systemd files in ${most_related_ver_d}/ for client's systemd service."
    echo "This may cause some problems to DRBL clients!"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    sleep 7
    cp ${most_related_ver_d}/systemd/system/ocsd-*.service $drbl_common_root/etc/systemd/system/
  fi
  ln -sf ocsd-rescue.service $drbl_common_root/etc/systemd/system/rescue.service
  rm -rf  $drbl_common_root/etc/rc*.d/S*ocs-run
fi

# copy those rcS.d services for Debian, this can only be done after all updata-rc.d finished. Otherwise it will affect the update-rc.d
if [ -e /etc/debian_version ]; then
   # Exclude those not necessary.
   # Put the service to be removed in $unnecessary_rcsd_srv if you have.
   RCS_D_EXCLUDE=""
   unnecessary_rcsd_srv=""
   for isv in $unnecessary_rcsd_srv; do
     RCS_D_EXCLUDE="$RCS_D_EXCLUDE --exclude=S*${isv} "
   done
   rsync -a $RCS_D_EXCLUDE /etc/rcS.d/* $drbl_common_root/etc/rcS.d/
   # Force to overwrite the modified networking service. We should not overwrite the symbolic link file for Ubuntu's client. It's linked to /lib/init/upstart-job
   if [ ! -L $drbl_common_root/etc/init.d/networking ]; then
     cp -af $drbl_setup_path/files/misc/networking $drbl_common_root/etc/init.d/
   fi
   # force to link some necessary services, since Knoppix or B2D won't have
   # them, but in DRBL, it's a must!!!
   (
     cd $drbl_common_root/etc/rcS.d/
     [ -f ../init.d/mountvirtfsn ] && ln -fs ../init.d/mountvirtfsn S02mountvirtfsn
     [ -f ../init.d/discover ] && ln -fs ../init.d/discover S36discover
     # B2D pureGnome 20051212 does not have hotplug* in rcS.d, but pureKDE has.
     # Anyway, for to link them.
     [ -f ../init.d/hotplug ] && ln -fs ../init.d/hotplug S40hotplug
     [ -f ../init.d/hotplug-net ] && ln -fs ../init.d/hotplug-net S41hotplug-net
     # change the hdparm from S07 to S60 (which is far after S41force-load-ide so we can access IDE device after IDE-related modules are loaded and ready).
     if [ -f ../init.d/hdparm ]; then
       [ -e "S07hdparm" ] && rm -f S07hdparm
       ln -fs ../init.d/hdparm S60hdparm
     fi
     [ -f ../init.d/portmap ] && ln -fs ../init.d/portmap S43portmap
     [ -f ../init.d/rpcbind ] && ln -fs ../init.d/rpcbind S43rpcbind
     [ -f ../init.d/mountnfs.sh ] && ln -fs ../init.d/mountnfs.sh S45mountnfs.sh
   )
   # modify some services which maybe not fit the requirement.
   # a. module-init-tools, since the method it detects rw is not quite well.
   if [ -e $drbl_common_root/etc/init.d/module-init-tools ]; then
     perl -pi -e 's|if \[ -w /lib/modules/\$KVER.*|if touch /lib/modules/\$KVER/modules.dep 2>/dev/null; then|g' $drbl_common_root/etc/init.d/module-init-tools
   fi
fi

vmware_as_server="$(grep "VMWare Inc" /proc/pci 2>/dev/null)"
# for VMWare, you have better to install the VMWare tools,
if [ -n "$vmware_as_server" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "It is VMWare as DRBL server ..., If you want to use X Window, make sure you already installed VMWare tools."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi
# First, clean the XF86Config,
# let configure (like redhat-cfg-xfree86) in /etc/init.d/firstboot
# to create the first one.
# Remove XF86Config and xorg.conf (Both for RH/MDK) in common root
# NOTE! We can NOT remove XF86Config-4/xorg.conf for Debian... it is a template, just rename it.
if [ -e /etc/debian_version ]; then
  # Debian
  for ix in XF86Config-4 xorg.conf; do
    [ -e "$drbl_common_root/etc/X11/$ix" ] && mv -f $drbl_common_root/etc/X11/${ix} $drbl_common_root/etc/X11/${ix}.drbl.template
  done
  # Debian Sarge does not sync the locale setting of gdm with system. do it
  if [ -f /etc/default/gdm ]; then
    # use subshell to avoid the running shell
    (
      # For B2D, it uses /etc/sysconfig/i18n...
      [ -e /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
      # the environment priority is higher then /etc/sysconfig/i18n
      [ -e /etc/environment ] && . /etc/environment
      if [ -n "$LANG" ]; then
        if grep -q "^[[:space:]]*#*[[:space:]]*LANG=.*" $drbl_common_root/etc/default/gdm 2>/dev/null; then
           perl -pi -e "s/^[[:space:]]*#*[[:space:]]*LANG=.*/LANG=$LANG/g" $drbl_common_root/etc/default/gdm
        else
           echo "LANG=$LANG" >> $drbl_common_root/etc/default/gdm
        fi
      fi
    )
  fi
else
  # RH-like
  for ix in XF86Config xorg.conf; do
    [ -e "$drbl_common_root/etc/X11/$ix" ] && rm -f $drbl_common_root/etc/X11/${ix}*
  done
fi

# Remove the firstboot setting to aviod it says NO
[ -f $drbl_common_root/etc/sysconfig/firstboot ] && rm -f $drbl_common_root/etc/sysconfig/firstboot
# Remove the /etc/reconfigSys to avoid firstboot run reconfig
[ -f $drbl_common_root/etc/reconfigSys ] && rm -f $drbl_common_root/etc/reconfigSys
# Disable the /usr/sbin/firstboot in the firstboot service, we should not reconfig ntp, user accounts for clients... This is for Redhat, Fedora...
if [ -e $drbl_common_root/etc/init.d/firstboot ]; then
  perl -p -i -e 's|^(\s*)(/usr/sbin/firstboot.*)$|$1true # $2 # Modified by DRBL|g' $drbl_common_root/etc/init.d/firstboot
fi

# Take care the hardware config files, clean old, make them be detected at boot.
if [ -e /etc/debian_version ]; then
  # Debian
  # In Debian, we need to keep the modules.conf* so that discover will work.
  # We can not force to put ide-cd ide-disk ide-generic  modules in /etc/modules (they are loaded by /etc/rcS.d/S20modutils), this will result chip driver (like piix and ide_core) is loaded afther them (by /etc/rcS.d/S40hotplut). This will cause a problem: unable to turn on IDE HD DMA ("HDIO_SET-DMA failed: Operation not permitted")
  # So we create a startup script after hotplug.
  if [ -f $drbl_common_root/etc/modules ]; then
    rm -f $drbl_common_root/etc/modules
    cat <<-MOD_END > $drbl_common_root/etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file should contain the names of kernel modules that are
# to be loaded at boot time, one per line.  Comments begin with
# a "#", and everything on the line after them are ignored.

# Note from DRBL:
# These modules are cleaned by DRBL drblpush so that we have a clean file.
# You can add any module you need here. But do not force to put ide-cd ide-disk ide-generic modules here, this will result chip driver (like piix and ide_core) is loaded afther them (by /etc/rcS.d/S40hotplut). This will cause a problem: unable to turn on IDE HD DMA ("HDIO_SET-DMA failed: Operation not permitted")
# DRBL will load ide-* in /etc/rcS.d/S41force-load-ide

MOD_END
  fi
  cp -f $drbl_setup_path/files/misc/force-load-ide $drbl_common_root/etc/init.d/force-load-ide
  prepare_update_rc_d_env $drbl_common_root/
  if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
    chroot $drbl_common_root/ insserv force-load-ide &> /dev/null
  else
    chroot $drbl_common_root/ /usr/sbin/update-rc.d force-load-ide start 41 S . &> /dev/null
  fi
elif [ -e /etc/SuSE-release ]; then
  # SuSE
  # No more force to put some almost-must modules (ide-disk...) in /etc/sysconfig/kernel, same reason with the Debian one.
  # Here we modify hwscan to let it run in boot.d and add a service "force-load-ide" in boot.d
  # hwscan only exists in SuSE 9.3, in 10.0 or later it's gone!
  create_insserv_env $drbl_common_root/
  for i in parse-load-mod-suse force-load-ide; do
    cp -f $drbl_setup_path/files/misc/$i $drbl_common_root/etc/init.d/
    chroot $drbl_common_root/ /sbin/insserv -f $i
  done
  # modify boot.idedma service to make it after force-load-ide
  if [ -e "$drbl_common_root/etc/init.d/boot.idedma" ]; then
    chroot $drbl_common_root/ /sbin/insserv -f -r boot.idedma
    perl -pi -e 's/^#[[:space:]]*Required-Start:.*/# Required-Start: boot.loadmodules force-load-ide/g' $drbl_common_root/etc/init.d/boot.idedma
    chroot $drbl_common_root/ /sbin/insserv -f boot.idedma
  fi
  # process the hwscan for SuSE 9.3
  if [ -e "$drbl_common_root/etc/init.d/hwscan" ]; then
    perl -pi -e 's/^#[[:space:]]*Default-Start:.*/# Default-Start: B/g' $drbl_common_root/etc/init.d/hwscan
    chroot $drbl_common_root/ /sbin/insserv -f hwscan
  fi
  # xfs need account nobody, which only exists in YP, so we have to make xfs runs after ypbind.
  if [ -e "$drbl_common_root/etc/init.d/xfs" ]; then
    if ! grep -Eq "^#[[:space:]]*Required-Start:.* ypbind" $drbl_common_root/etc/init.d/xfs; then
      perl -pi -e 's/(^#[[:space:]]*Required-Start:.*)/$1 ypbind/g' $drbl_common_root/etc/init.d/xfs
    fi
    chroot $drbl_common_root/ /sbin/insserv -f xfs
  fi
  # To avoid the loop error (i.e. haldaemon need nfs, nfs need network, network need haldaemon, we remove haldaemon in network. Then we can make haldaemon after nfs. (Although network service is not enabled in client, but we still have to do this modification.) without "chroot $drbl_common_root/ /sbin/insserv -f network" it.
  if [ -e "$drbl_common_root/etc/init.d/network" ]; then
    chroot $drbl_common_root/ /sbin/insserv -f -r network
    perl -pi -e 's/(^#[[:space:]]*Required-Start:.*)haldaemon/$1/g' $drbl_common_root/etc/init.d/network
    chroot $drbl_common_root/ /sbin/insserv -f network
  fi
  # modify haldaemon service to make it after nfs, since
  # ldd /usr/sbin/hald:
  #  ...
  #  libgobject-2.0.so.0 => /opt/gnome/lib/libgobject-2.0.so.0 (0xb7ec9000)
  #  libglib-2.0.so.0 => /opt/gnome/lib/libglib-2.0.so.0 (0xb7e43000)
  #  libdbus-1.so.2 => /usr/lib/
  #  ...
  # so we need to make it after NFS directories (/usr/, /opt) are mounted.
  if [ -e "$drbl_common_root/etc/init.d/haldaemon" ]; then
    chroot $drbl_common_root/ /sbin/insserv -f -r haldaemon
    perl -pi -e 's/^#[[:space:]]*Required-Start:.*/# Required-Start:	boot.localnet dbus nfs/g' $drbl_common_root/etc/init.d/haldaemon
    chroot $drbl_common_root/ /sbin/insserv -f haldaemon
  fi
  #
else
  # RH-like
  # Only for RH-like distribution, we can remove the modules.conf*
  # remove the etc/modules.conf in template so that the kudzu in the client can create their own hardware config file.
  # In Debian, we need to keep the modules.conf* so that discover will work.
  find $drbl_common_root/etc/ -name "modules.conf*" -exec rm -f {} \;
fi

# remove the script in rc[0,6].d to let the client can halt and reboot
if [ -e /etc/debian_version ]; then
  # Debian
  # For Debian, we use update-rc.d to assign which level run which program, so
  # no networking & umountnfs.sh
  true
elif [ -e /etc/SuSE-release ]; then
  # SuSE
  client_halt_reboot_runlevel_must_remove_srv="nfs network"
  for i in $client_halt_reboot_runlevel_must_remove_srv; do
     # Note! Only for K[0-9][0-9]*, since nfs is nfs client in SuSE, we need it
     # to start, but do not want it to be killed when change runlevel, reboot
     # or halt.
     rm -f $drbl_common_root/etc/init.d/rc[123456].d/K[0-9][0-9]$i
  done
else
  # RH-like
  client_halt_reboot_runlevel_must_remove_srv="netfs network killall"
  for i in $client_halt_reboot_runlevel_must_remove_srv; do
     rm -f $drbl_common_root/etc/rc[06].d/[SK][0-9][0-9]$i
  done
fi

# force to disable selinux in the client.
for ise in /etc/selinux/config /etc/sysconfig/selinux; do
  if [ -f $drbl_common_root/$ise ]; then
    perl -pi -e "s/^SELINUX=.*/SELINUX=disabled/g" $drbl_common_root/$ise
  fi
done

# remove the template's etc/sysconfig/hwconf which kudzu will log
[ -f $drbl_common_root/etc/sysconfig/hwconf ] && rm -f $drbl_common_root/etc/sysconfig/hwconf

# Prepare the critical program mount.nfs, since some lib could be in /usr/lib/ (e.g. Fedora 12 or Mandriva 2010.0).
# Variable DESTDIR is required for copy_exec_drbl use
export DESTDIR="$drbl_common_root"
[ -e "/sbin/mount.nfs" ] && copy_exec_drbl /sbin/mount.nfs /sbin/

# The root over NFS mount is done in sbin/init which Steven modified,
# $nfsserver:$drbl_common_root
# so remove this file
[ -f $drbl_common_root/etc/fstab ] && rm -f $drbl_common_root/etc/fstab

# clean the rhn config, client should not do that.
[ -d $drbl_common_root/etc/sysconfig/rhn ] && rm -rf $drbl_common_root/etc/sysconfig/rhn 2> /dev/null

# Before copying init.drbl as $drbl_common_root/sbin/init (copyied in the
# revious rsync command), we'd better to remove $drbl_common_root/sbin/init
# therwise if it's a symbolic file, which might cause the server /sbin/init
# o fail. This is the case in systemd:
# lrwxrwxrwx 1 root root 20 Apr 17 09:37 /sbin/init -> /lib/systemd/systemd*
rm -f $drbl_common_root/sbin/init
cp -f $drbl_setup_path/files/misc/init.drbl $drbl_common_root/sbin/init
# Find if the dir /run is mounted as tmpfs. If not, disable that for client.
run_fs="$(LC_ALL=C df -T /run 2>/dev/null |grep -Ew "/run" | awk -F" " '{print $1}')"
if [ "$run_fs" != "tmpfs" ]; then
  perl -pi -e "s/^TMPFS_RUN=.*/TMPFS_RUN=\"false\" # Enabled by drblpush./g" $drbl_common_root/sbin/init
fi
chown root:root $drbl_common_root/sbin/init
chmod 755 $drbl_common_root/sbin/init

# mkdir special directory etc/diskless-image for each diskless host to mount its fstab
#
mkdir -p $drbl_common_root/etc/diskless-image

# copy dev tarball to $drbl_common_root/etc/diskless-image
# For older version of udev, we test udevd, for newer one, we test udevadm
if [ -x "$drbl_common_root/usr/sbin/udevadm" -o \
     -x "$drbl_common_root/usr/bin/udevadm" -o \
     -x "$drbl_common_root/usr/sbin/udevd" ]; then
  echo -n "Using udev for clients... "
elif [ -f "$drbl_pkgdir/dev.tgz" ]; then
  echo -n "Using old-style dev for clients... "
  cp -f $drbl_pkgdir/dev.tgz $drbl_common_root/etc/diskless-image
else
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "Can NOT find udev or the dev.tgz, did you already setup the DRBL server ?"
  echo "Please press Ctrl-C to stop the program!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  read
  exit 1
fi

# Switch client graphic/text mode
case "$OS_type" in
RH|MDK|SUSE)
  # set the init to user specifies
  case "$client_init" in
    "text")
          CLIENT_INIT_RL=3
          ;;
    "graphic")
          CLIENT_INIT_RL=5
          ;;
  esac
  # systemd-liked use /etc/systemd/system/default.target link to default runlevel
  [ -L "$drbl_common_root/etc/systemd/system/default.target" ] && ln -fsv /lib/systemd/system/runlevel${CLIENT_INIT_RL}.target $drbl_common_root/etc/systemd/system/default.target || perl -p -i -e "s/^id:[1-5]:initdefault:/id:$CLIENT_INIT_RL:initdefault:/g" $drbl_common_root/etc/inittab
  ;;
DBN)
  default_dm="$(drbl-check-dm 2> /dev/null)"
  if [ -n "$default_dm" ]; then
    case "$client_init" in
      "text")
          echo "Set text mode for Debian DRBL client..."
          prepare_update_rc_d_env $drbl_common_root/
          if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
            chroot $drbl_common_root/ insserv -f -r $default_dm &> /dev/null
          else
            chroot $drbl_common_root/ /usr/sbin/update-rc.d -f $default_dm remove &> /dev/null
          fi
          #clean_update_rc_d_env $drbl_common_root/
	  # For upstart 0.6.3 (Ubuntu 9.10) or later it uses /etc/init/*.conf
	  if [ -e "$drbl_common_root/etc/init/${default_dm}.conf" ]; then
            switch_upstart_service $drbl_common_root/etc/init/${default_dm}.conf off
	  fi
          ;;
      "graphic")
        if [ -n "$default_dm" ]; then
          echo "Set graphic mode for Debian DRBL client..."
          prepare_update_rc_d_env $drbl_common_root/
          # gdm should be later than nis (S12), and should be later than hal (S24)
          if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
            chroot $drbl_common_root/ insserv $default_dm &> /dev/null
          else
            chroot $drbl_common_root/ /usr/sbin/update-rc.d $default_dm start 30 2 3 4 5 . stop 01 0 1 6 . &> /dev/null
          fi
          #clean_update_rc_d_env $drbl_common_root/
	  # For upstart 0.6.3 (Ubuntu 9.10) or later it uses /etc/init/*.conf
	  if [ -e "$drbl_common_root/etc/init/${default_dm}.conf" ]; then
            switch_upstart_service $drbl_common_root/etc/init/${default_dm}.conf on
	  fi
        fi
        ;;
    esac
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "The default display manager is NOT found! We can NOT set text or graphic mode for Debian DRBL client."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
  ;;
esac

# Turn off all the xinted/inted services in clients.
# Set the tftpd to on when xinetd/inted starts in server.
# (1) for client:
if [ -e /etc/debian_version ]; then
  # Debian
  if grep -q "^tftp[[:space:]]+" $drbl_common_root/etc/inetd.conf 2>/dev/null; then
    # Note: /usr/sbin/update-inetd is perl, and require some perl modules.
    # It need /usr/share/perl5/DebianNet.pm, but it depends on perl version.
    #chroot $drbl_common_root /usr/sbin/update-inetd --remove tftp
    # Here we use easier method, just delete the tftp in /etc/inetd.conf
    # It looks like:
    # tftp           dgram   udp     wait    root  /usr/sbin/in.tftpd /usr/sbin/in.tftpd -s /var/lib/tftpboot
    perl -pi -e "s/^tftp[[:space:]]+.*//g" $drbl_common_root/etc/inetd.conf
  fi
  if [ -e $drbl_common_root/etc/init.d/tftpd-hpa ]; then
    # it's a standalone daemon
    prepare_update_rc_d_env $drbl_common_root/
    if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
      chroot $drbl_common_root/ insserv -f -r tftpd-hpa &> /dev/null
    else
      chroot $drbl_common_root/ /usr/sbin/update-rc.d -f tftpd-hpa remove &> /dev/null
    fi
  fi
else
  # RH-like & SuSE
  perl -p -i -e "s/disable.*=.*/disable                 = yes/g" $drbl_common_root/etc/xinetd.d/tftp
fi

# (2) for server
if [ -n "$(getenforce 2>/dev/null)" -a "$(getenforce 2>/dev/null)" = "Enforcing" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "SELinux is 'Enabled' !! Please disable it or make it to work with DRBL relative service "
  sleep 10
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi
# Disable FirewallD
if [ "$(LC_ALL=C firewall-cmd --state 2>/dev/null)" = "running" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "'Firewlld' would be DISABLED and stop , then replace with iptables service !!!"
  systemctl stop firewalld.service
  systemctl disable firewalld.service
  sleep 10
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

# set the tftp to on when xinetd/inted starts and portmap or rpcbind settings in server.
if [ -e /etc/debian_version ]; then
  # Debian
  # (1) tftpd
  # Force to remove tftpd in inetd if it's set, and we will add it later
  # and put our arguments "-s /tftpboot/nbi_img"
  if grep -q "^tftp" /etc/inetd.conf 2>/dev/null; then
    /usr/sbin/update-inetd --remove tftp
  fi
  if [ -e /etc/init.d/tftpd-hpa ]; then
    # Patch the /etc/init.d/tftp-hpa, the "set -e" should not be put otherwise
    # if tftpd-hpa is not started, "/etc/init.d/tftpd-hpa restart" (insted of
    # "/etc/init.d/tftpd-hpa start") will just stop and fail, will not start it.
    perl -p -i -e "s/^[[:space:]]*set -e.*/#set -e/g" /etc/init.d/tftpd-hpa

    # From tftpd-hpa 5.0, the config file is different
    # /etc/init.d/tftpd-hpa is for Debian, while /etc/init/tftpd-hpa.conf is for Ubuntu's upstart
    if [ -n "$(grep -E TFTP_DIRECTORY /etc/init.d/tftpd-hpa 2>/dev/null)" -a \
         -n "$(grep -E TFTP_USERNAME /etc/init.d/tftpd-hpa 2>/dev/null)" ] || \
       [ -n "$(grep -E TFTP_DIRECTORY /etc/init/tftpd-hpa.conf 2>/dev/null)" -a \
         -n "$(grep -E TFTP_USERNAME /etc/init/tftpd-hpa.conf 2>/dev/null)" ]; then
      # Version 5.0 or later.
      cat <<-TFTP_END > /etc/default/tftpd-hpa
TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/tftpboot/nbi_img"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--secure --ipv4"
TFTP_END
    else
      # Version 0.49 or before.
      # it's a standalone daemon
      cat <<-TFTP_END > /etc/default/tftpd-hpa
RUN_DAEMON="yes"
OPTIONS="-l -s /tftpboot/nbi_img"
TFTP_END
    fi
    # (2) Portmap. From portmap (6.0-11), when new installation, default the question whether to bind to the loopback interface only. We have to open it.
    if [ -e /etc/default/portmap ]; then
      perl -pi -e 's/^(OPTIONS=.*)/#$1 # Commented by DRBL/g' /etc/default/portmap
    fi
  else
    # it's a daemon in inetd, set it in inetd.conf
    /usr/sbin/update-inetd --group BOOT --add 'tftp	dgram	udp	wait	root	/usr/sbin/in.tftpd	/usr/sbin/in.tftpd	-s /tftpboot/nbi_img'
  fi
else
  # RH-like & SuSE
  if [ -e /etc/xinetd.d/tftp ]; then
    # set the tftp working directory to be /tftpboot/nbi_img
    # to have higher security.
    perl -p -i -e "s/disable.*=.*/disable                 = no/g" /etc/xinetd.d/tftp
    perl -p -i -e "s/server_arg.*=.*/server_args		= -s \/tftpboot\/nbi_img/g"  /etc/xinetd.d/tftp
  fi
  # For systemd distr. , ex: Fedora 21
  if [ -e /usr/lib/systemd/system/tftp.service ]; then
    perl -p -i -e "s/^(ExecStart=\S*)[[:space:]]+.*$/\$1 -s \/tftpboot\/nbi_img/g" /usr/lib/systemd/system/tftp.service
  fi
fi

# create a config file for each diskless host to mount its fstab
# Steven to do, what's master ?
cat <<-CONFIG_END > $drbl_common_root/etc/diskless-image/config

nfsserver_default=$nfsserver_default
nfsimagedir=$drbl_common_root
nfshostsdir=$drblroot
nameserver="$nameserver"

CONFIG_END

# for clients' public IP
# if the file $public_ip_list is created, copy it
[ -f "$public_ip_list" ] && cp -f $public_ip_list $drbl_common_root/etc/diskless-image/

# copy the collected MAC addresses to drbl sysconfig
if [ "$collect_mac" = "yes" ]; then
  cp -f macadr-*.txt $drbl_syscfg/ &> /dev/null
fi

# write the resolv.conf
# //NOTE// For resolvconf on Ubuntu 12.04, the /etc/resolv.conf is linked to /run/resolvconf/resolv.conf, which is a tmpfs file system. Here just remove it.
rm -f $drbl_common_root/etc/resolv.conf

for nameserver in $nameserver_; do
  echo "nameserver $nameserver" >> $drbl_common_root/etc/resolv.conf
done

# rc.sysinit only in RH-like (BSD), no rc.sysinit in Debian/SuSE
case "$OS_type" in
  RH|MDK)
    # For distribution RH/FC/CO/MDK/MDV
    if [ -f "${drbl_setup_path}/files/${OS_type}/${OS_Version}/rc.sysinit.${OS_Version}.drbl" ]; then
      cp -f ${drbl_setup_path}/files/${OS_type}/${OS_Version}/rc.sysinit.${OS_Version}.drbl $drbl_common_root/etc/rc.d/rc.sysinit
    else
      # Can not find fine-tune file, show warning. This is only necessary for CentOS <= 6, since for Fedora, when >= version 17, no required. //NOTE// From drbl 2.x, only CentOS and Fedora are supported.
      OS_Version_Major="${OS_Version:0:3}"  # E.g. CO5.8 -> CO5
      case "$OS_Version" in
        CO*)
        if ! is_systemd_init; then
          most_related_ver="$(LC_ALL=C find $drbl_setup_path/files/$OS_type/${OS_Version_Major}* -type d -exec basename {} \; 2>/dev/null | sort | uniq | tail -n 1)"
          [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
          echo "Warning! The fine-tune file ${drbl_setup_path}/files/${OS_type}/${OS_Version}/rc.sysinit.${OS_Version}.drbl was not found. Using ${drbl_setup_path}/files/${OS_type}/${most_related_ver}/rc.sysinit.${most_related_ver}.drbl as /etc/rc.d/rc.sysinit for DRBL clients!"
          echo "This may cause some problems to DRBL clients!"
          [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
          [ -n "$most_related_ver" ] && cp -f ${drbl_setup_path}/files/${OS_type}/${most_related_ver}/rc.sysinit.${most_related_ver}.drbl $drbl_common_root/etc/rc.d/rc.sysinit
	fi
	;;
      esac
    fi
    ;;
esac

# "ln -fs tmp/boot/ boot" in template
# insert "mkdir tmp/boot" in rc.sysinit of other clients, because it's tmpfs
# so that /sbin/mkkerneldoth in rc.sysinit can creat file "/boot/boot.h"
if [ ! -L "$drbl_common_root/boot" ]; then
  (cd $drbl_common_root; ln -fs tmp/boot boot)
fi

# create the CLEAN rc.boot/boot.local/rc.local to avoid some commands copied from server
if [ -e /etc/debian_version ]; then
  # Debian
  [ -d "$drbl_common_root/etc/rc.boot" ] && rm -f $drbl_common_root/etc/rc.boot/*
elif [ -e /etc/SuSE-release ]; then
  # SuSE
  if [ -f "$drbl_common_root/etc/init.d/boot.local" ]; then
    perl -pi -e "s/^[[:space:]]*[^#]+//g" $drbl_common_root/etc/init.d/boot.local
  fi
else
  # RH-like
  # 1st, clean rc.local
  [ -f $drbl_common_root/etc/rc.d/rc.local ] && rm -f $drbl_common_root/etc/rc.d/rc.local

  # 2nd, create a clean rc.local
  cat <<-RC_LOCAL > $drbl_common_root/etc/rc.d/rc.local
#!/bin/bash
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.
export PATH=\$PATH:$DRBL_SCRIPT_PATH/sbin:$DRBL_SCRIPT_PATH/bin

touch /var/lock/subsys/local

# For Mandrake, harddrake will not create cdrom link automatically... so
# detect it and create it.
# While for Redhat, kudzu will do that. Anyway, we just do it.
if [ ! -e "/dev/cdrom" ]; then
  cddev="\$(drbl-detect-cdrom)"
  [ -n "\$cddev" ] && ln -fs /dev/\$cddev /dev/cdrom
fi

# For Mandrake, it use /mnt (tmpfs) instead of /media for cdrom, floppy, create the mount point in tmpfs, since mandrake does not create them automatically.
# Although the problem is only in mandrake, but we still create them for all RH-like dists, since user maybe want to use these mount points.
for d in floppy cdrom loop disk usb; do
  [ ! -d "/mnt/\$d" ] && mkdir -p /mnt/\$d
done

RC_LOCAL

  #change its mode
  chown root:root $drbl_common_root/etc/rc.d/rc.local
  chmod 775 $drbl_common_root/etc/rc.d/rc.local
fi

# Modify some rc programs.
# For RH-like, use the modified template etc/init.d/halt, which remove all the umount command
# For Debian and SuSE, just use perl to modify them.
if [ -e /etc/debian_version ]; then
  # Debian
  # For genuine Debian
  # remove -i in "reboot -d -f -i" so it won't stop network before reboot
  # remove -i in "halt -d -f -i -p" so it won't stop network before halt
  if [ -e $drbl_common_root/etc/init.d/reboot ]; then
    perl -pi -e 's/^([[:space:]]*reboot .*)-i(.*)/$1 $2 # Modified by DRBL/' $drbl_common_root/etc/init.d/reboot
  fi
  if  [ -e $drbl_common_root/etc/init.d/halt ]; then
    perl -pi -e 's/^([[:space:]]*halt .*)-i(.*)/$1 $2 # Modified by DRBL/' $drbl_common_root/etc/init.d/halt
  fi
  # For B2D, the reboot and halt is a little different, except the above,
  # we have to comment umount -a
  if [ -e $drbl_common_root/etc/init.d/reboot ]; then
    perl -pi -e 's/^([[:space:]]*umount -a.*)/#$1 # Modified by DRBL/' $drbl_common_root/etc/init.d/reboot
  fi
  if [ -e $drbl_common_root/etc/init.d/halt ]; then
    perl -pi -e 's/^([[:space:]]*umount -a.*)/#$1 # Modified by DRBL/' $drbl_common_root/etc/init.d/halt
  fi
  # To force do not turn off network when rebooting/halting.
  if grep -Eq "^NETDOWN=" $drbl_common_root/etc/init.d/halt 2>/dev/null; then
    # If we found "NETDOWN=..." in /etc/init.d/halt, force to write NETDOWN=no in client's /etc/default/halt
    if ! grep -Eq "^NETDOWN=" $drbl_common_root/etc/default/halt 2>/dev/null; then
      echo "NETDOWN=no  # Modified by DRBL" >> $drbl_common_root/etc/default/halt
    else
      if [ -e $drbl_common_root/etc/default/halt ]; then
        perl -pi -e 's/^NETDOWN=.*/NETDOWN=no # Modified by DRBL/' $drbl_common_root/etc/default/halt
      fi
    fi
  fi
  # Disable the /lib/init/rw removinig. Otherwise harmless errors will be shown during clents booting.
  if [ -e /lib/init/bootclean.sh ]; then
    LC_ALL=C perl -pi -e 's|(^[[:space:]]*)(clean /lib/init/rw "! -type d".*$)|$1#$2 # Modified by DRBL|g' $drbl_common_root/lib/init/bootclean.sh
  fi

  # Do not clean or remove etc/mtab when boots, and force not to update etc/mtab
  if [ -e $drbl_common_root/etc/init.d/checkroot.sh ]; then
    perl -pi -e 's|^([[:space:]]*:> $MTAB_PATH.*)|#$1 # Modified by DRBL|' $drbl_common_root/etc/init.d/checkroot.sh
    perl -pi -e 's|^([[:space:]]*rm -f \$\{MTAB_PATH\}~.*)|#$1 # Modified by DRBL|' $drbl_common_root/etc/init.d/checkroot.sh
    perl -pi -e 's|^([[:space:]]*)INIT_MTAB_FILE=yes|$1 INIT_MTAB_FILE=no # Modified by DRBL|' $drbl_common_root/etc/init.d/checkroot.sh
  fi
  if [ -e $drbl_common_root/etc/init.d/checkfs.sh ]; then
    # Do not remove /fastboot, DRBL client is always fastboot
    perl -pi -e 's|^([[:space:]]*rm -f )(/fastboot)(.*)|$1 $3 # modified by DRBL|' $drbl_common_root/etc/init.d/checkfs.sh
  fi
  # bootmisc.sh will prevent client to login by showning
  # "System bootup in progress - please wait" > /etc/nologin
  # We must avoid /etc/nologin to be created by set DELAYLOGIN=no in client's /etc/default/rcS
  if [ -e $drbl_common_root/etc/default/rcS ]; then
    perl -pi -e 's|^[[:space:]]*DELAYLOGIN=.*|DELAYLOGIN=no # modified by DRBL|' $drbl_common_root/etc/default/rcS
  fi

  if [ -x "$drbl_common_root/etc/init.d/linux-restricted-modules-common" ]; then
    # $drbl_common_root/lib/modules/$KERNEL_VER/volatile is already created in drblsrv-offline for Ubuntu. Here we have to modify linux-restricted-modules-common service so that it can write in /lib/modules/$KERNEL_VER/volatile, otherwise it is Read-Only NFS filesystem.
    # /sbin/lrm-manager --quick ->
    # mount -n -t tmpfs tmpfs /lib/modules/`uname -r`/volatile; /sbin/lrm-manager --quick # Modified by DRBL
    perl -pi -e 's|^([[:space:]]*)(/sbin/lrm-manager --quick.*)|$1mount -n -t tmpfs tmpfs /lib/modules/`uname -r`/volatile; $2 # Modified by DRBL|g' $drbl_common_root/etc/init.d/linux-restricted-modules-common
  fi

  # Debian Etch has NetworkManager/NetworkManagerDispatcher under dbus, we can not let it start in client. Otherwise the network in client will be reset.
  rm -f $drbl_common_root/etc/dbus-1/event.d/[0-9][0-9]NetworkManager*

  # Making mountkernfs.sh and mountdevsubfs.sh start with updating /etc/mtab, otherwise when it's run 2nd time with reload (mountkernfs.sh reload), it will complain that
  # mount: can't find /run/lock in /etc/fstab or /etc/mtab
  # mount: can't find /run/shm in /etc/fstab or /etc/mtab
  # This is for Debian Jessie because mountkernfs.sh and mountdevsubfs.sh use different flag than that in Wheezy and Squeeze.
  # start)
  #       mount_filesystems mount_noupdate -> mount_filesystems mount
  #       ;;
  for i in mountkernfs.sh mountdevsubfs.sh; do
    if [ -e $drbl_common_root/etc/init.d/$i ]; then
      perl -pi -e 's|^([[:space:]]*)mount_filesystems mount_noupdate|$1mount_filesystems mount # modified by DRBL|' $drbl_common_root/etc/init.d/$i
    fi
  done
  # For Ubuntu dapper, /etc/init.d/mountnfs.sh is no more, and moved to /etc/network/if-up.d/mountnfs.sh. It will be run when ifup starts successfully in networking service. However, in DRBL client, network is actually started in initrd.
  # For Debian testing (on 2006/09/15), the mountnfs.sh from initscripts 2.86.ds1-19 or later use the same skill with waitnfs.sh, but it's name is mountnfs.sh. Hence we have to use the keyword "Wait for network file systems" to judge that, since in the mountnfs.sh, there is:
# Short-Description: Wait for network file systems to be mounted
  # Ugly! This is a workaround, it's better to make the ifup command work in /etc/init.d/networking, then the /etc/network/if-up.d/mountnfs.sh can be run in client.
  use_start_srv_after_ifup="no"
  if grep -q -E "Wait for network file systems" $drbl_common_root/etc/init.d/mountnfs.sh 2>/dev/null; then
    use_start_srv_after_ifup="yes"
  elif [ -e $drbl_common_root/etc/init.d/waitnfs.sh ]; then
    use_start_srv_after_ifup="yes"
  fi
  if [ "$use_start_srv_after_ifup" = "yes" ]; then
    # mountnfs.sh is called in start-srv-after-ifup
    cp -af $drbl_setup_path/files/misc/start-srv-after-ifup $drbl_common_root/etc/init.d/
    for infsf in waitnfs.sh mountnfs.sh; do
     if [ -e $drbl_common_root/etc/init.d/$infsf ]; then
      # Here we also insert a line to create a dir /tmp/boot (/tmp is tmpfs so we have to use a service to do that everytime client boots) so the /boot link to /tmp/boot/ will work.
      # case (1): The function name is do_start (dapper)
      perl -pi -e 's|(^[[:space:]]*)do_start([[:space:]]*$)|$1/etc/init.d/start-srv-after-ifup; mkdir -p /tmp/boot; do_start # Modified by DRBL $2|' $drbl_common_root/etc/init.d/$infsf
      # case (2): The function name is do_wait_async_mount (etch), in this case
      # We'd better to force ASYNCMOUNTNFS=yes in /etc/default/rcS
      perl -pi -e 's|(^[[:space:]]*)do_wait_async_mount([[:space:]]*$)|$1/etc/init.d/start-srv-after-ifup; mkdir -p /tmp/boot; do_wait_async_mount # Modified by DRBL $2|' $drbl_common_root/etc/init.d/$infsf
      # mountnfs.sh is buggy, too. Actually it's mountpoint bug, which failed to identify some mount point as mount point, e.g. /usr/ and /var (mounted in init.drbl)
      # https://bugs.launchpad.net/ubuntu/+source/sysvinit/+bug/93634
      # A workaround is (1) not to put "/usr/" and "/var" in the list and (2) shorten the TIMEOUT.
      # Code for (1) to be commented in mountnfs.sh from Debian Lenny/Squeeze:
      #	case "$MTPT" in
      #	  /usr/local|/usr/local/*)
      #		;;
      #	  /usr|/usr/*)
      #		waitnfs="$waitnfs $MTPT"
      #		;;
      #	  /var|/var/*)
      #		waitnfs="$waitnfs $MTPT"
      #		;;
      #	esac
      # (1)
      mountnfs_file="$drbl_common_root/etc/init.d/$infsf"
      case_to_be_commented="usr var"
      for i in $case_to_be_commented; do
        chk_line_no="$(LC_ALL=C grep -n -F -- "/$i|/$i/*)" $mountnfs_file | cut -d":" -f1)"
        [ -z "$chk_line_no" ] && continue
        chk_next_line="$((chk_line_no + 1))"
        perl -pi -e "if (${chk_next_line}..${chk_next_line}) {s/^([[:space:]]+)(waitnfs=.*)/\$1#\$2   # Modified by DRBL/g}" $mountnfs_file
      done
      # (2)
      perl -pi -e 's/^([[:space:]]+)TIMEOUT=[[:digit:]]+/$1TIMEOUT=30 # Modified by DRBL/g' $drbl_common_root/etc/init.d/$infsf
      perl -pi -e 's|^[[:space:]]*ASYNCMOUNTNFS=.*|ASYNCMOUNTNFS=yes # Modified by DRBL|g' $drbl_common_root/etc/default/rcS
     fi
    done
  fi
  # UGLY!
  # The upstart (/etc/event.d/rc-default) in Ubuntu 6.10 to 9.04 is buggy, it does not honor the [013456] in /proc/cmdline
  # Ref: https://launchpad.net/ubuntu/+source/upstart/+bug/85014
  # It's fixed in Ubuntu 9.10 or later.
  [ -e /etc/lsb-release ] && . /etc/lsb-release
  if [ "$DISTRIB_ID" = "Ubuntu" ]; then
    case "$DISTRIB_RELEASE" in
     "6.10")
        cp -f $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/rc-default  $drbl_common_root/etc/event.d/rc-default
        # For ubuntu 6.10-7.10 upstart problem.
        # Ref: https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/65230
        # Change the contents of /etc/event.d/tty[1-6]:
        # start on runlevel 2 -> start on stopped rc2
        for i in $drbl_common_root/etc/event.d/tty[0-9]; do
          perl -pi -e "s/^start on runlevel /start on stopped rc/g" $i
        done
	;;
     "7.04"|"7.10"|"8.04"|"8.10"|"9.04")
        cp -f $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/rc-default  $drbl_common_root/etc/event.d/rc-default
        # For ubuntu 6.10-7.10 upstart problem.
        # Ref: https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/65230
        # Change the contents of /etc/event.d/tty[1-6]:
        # start on runlevel 2 -> start on stopped rc2
        for i in $drbl_common_root/etc/event.d/tty[0-9]; do
          perl -pi -e "s/^start on runlevel /start on stopped rc/g" $i
        done
        # Disable the recovery-menu, use sulogin, otherwise the error messages of Clonezilla will be overwritten.
        if [ -e "$drbl_common_root/etc/event.d/rcS-sulogin" ]; then
          perl -pi -e "s|(^[[:space:]]*) /usr/share/recovery-mode/recovery-menu.*|\$1 /sbin/sulogin # Modified by DRBL. Force to use sulogin!|g" $drbl_common_root/etc/event.d/rcS-sulogin
        fi
	;;
     "9.10")
        # The released rc-sysinit.conf is buggy. We use the one we patched.
        cp -af $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/rc-sysinit.conf $drbl_common_root/etc/init/rc-sysinit.conf
        cp -af $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/drbl-client-boot.conf $drbl_common_root/etc/init/drbl-client-boot.conf
	;;
     *)
        # For Ubuntu 10.04 or later.
	if [ -e "$drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/drbl-client-boot.conf" ]; then
          cp -af $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/drbl-client-boot.conf $drbl_common_root/etc/init/drbl-client-boot.conf
	else
          if ! is_systemd_init; then
	    # Only show this for upstart
            [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
            echo "Warning! Unable to find the fine-tune file $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/drbl-client-boot.conf, use $drbl_setup_path/files/Ubuntu/drbl-client-boot-default.conf for DRBL clients!"
            echo "This may cause some problems to DRBL clients!"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
            cp -af $drbl_setup_path/files/Ubuntu/drbl-client-boot-default.conf $drbl_common_root/etc/init/drbl-client-boot.conf
	  fi
	fi
	if [ -e "$drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/S00wait-drbl" ]; then
          cp -af $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/S00wait-drbl $drbl_common_root/etc/rcS.d/
	else
          if ! is_systemd_init; then
	    # Only show this for upstart
            [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
            echo "Warning! Unable to find the fine-tune file $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/S00wait-drbl, use $drbl_setup_path/files/Ubuntu/S00wait-drbl-default for DRBL clients!"
            echo "This may cause some problems to DRBL clients!"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
            cp -af $drbl_setup_path/files/Ubuntu/S00wait-drbl-default $drbl_common_root/etc/init/S00wait-drbl
	  fi
	fi
	# For plymouth.conf, we won't let plymouthd to run in rc=1, even with --mode=shutdown, otherwise when running clonezilla job in the client, the initial screen might be in vt 7, and the clonezilla job is run at vt 1.
	if [ -e "$drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/plymouth.conf" ]; then
	  # Use the customized plymouth.conf.
          cp -af $drbl_setup_path/files/Ubuntu/$DISTRIB_RELEASE/plymouth.conf $drbl_common_root/etc/init/plymouth.conf
	else
          if [ "$DISTRIB_RELEASE" \< 13.10 ]; then
            # Here if we use the override file like the following for
	    # Ubuntu 13.10,
	    # the client won't be able to enter lightdm, only stay in text mode.
	    # This is OK for Clonezilla mode, but not for DRBL mode. This issue
	    # is fixed on Ubuntu 13.10.
	    # //NOTE// Here we can not use function switch_upstart_service because it will stop all, howerver, we only want to disable part of its action for Ubuntu < 13.10 otherwise it won't be able to enter lightdm.
	    perl -pi -e 's|^([[:space:]]*)(exec /sbin/plymouthd --mode=shutdown)|$1true #$2 # Commented by DRBL to avoid no Clonezilla SE output messages on console 1|g' $drbl_common_root/etc/init/plymouth.conf
	    #perl -pi -e 's|^([[:space:]]*)(exec /sbin/plymouthd --mode=boot --attach-to-session)|$1true #$2 # Commented by DRBL to avoid no Clonezilla SE output messages on console 1|g' $drbl_common_root/etc/init/plymouth.conf
	    #perl -pi -e 's|^([[:space:]]*)(exec /bin/plymouth show-splash)|$1true #$2 # Commented by DRBL to avoid no Clonezilla SE output messages on console 1|g' $drbl_common_root/etc/init/plymouth.conf
          elif [ "$DISTRIB_RELEASE" \< 14.10 ]; then
	    # 2018/02/09 Comment all. It seems for Ubuntu 14.04 the default behavior is OK now.
            # Ubuntu 13.10 - 14.04.
            # For upstart (>1.3) service, we can use override file (Ref: http://upstart.ubuntu.com/cookbook/#override-files)
	    # echo "manual" > $drbl_common_root/etc/init/plymouth.override
	    # For Ubuntu 14.04 or later, a command about plymouth was added in /etc/init/rc.conf. We have to disable it otherwise it will switch to vt7 but rc1 (where S19ocs-run is, especially for select-in-client mode of clonezilla) is still in vt1.
	    # perl -pi -e 's|^([[:space:]]*)(status plymouth-shutdown.*start wait-for-state WAITER=rc WAIT_FOR=plymouth-shutdown.*)|$1true #$2 # Commented by DRBL to keep the services in rc in same console|g' $drbl_common_root/etc/init/rc.conf
	    true
	  else
            # Ubuntu 14.10 or later.
	    # For Ubuntu 14.10 plymouth service is a must for client to start all required service,
	    # Therefore we can not disable it.
	    # For Ubuntu 14.04 or later, a command about plymouth was added in /etc/init/rc.conf. We have to disable it otherwise it will switch to vt7 but rc1 (where S19ocs-run is, especially for select-in-client mode of clonezilla) is still in vt1.
	    perl -pi -e 's|^([[:space:]]*)(status plymouth-shutdown.*start wait-for-state WAITER=rc WAIT_FOR=plymouth-shutdown.*)|$1true #$2 # Commented by DRBL to keep the services in rc in same console|g' $drbl_common_root/etc/init/rc.conf
	    # Somehow the unnecessary services in client's /etc/rcS.d/ cause the console behaves weird... like:
	    # (1) The TUI output of partclone is distored
	    # (2) Keyboard does not work well in the mode "select-in-client"
	    # Therefore we just remove all of them except S00wait-drbl. It's OK to do so because all the required services are actually started by upstart already.
	    # //NOTE// This workaround does not work well. It will cause client fails to reboot/shtudown. Therefore we can not use it.
            # if [ "$DISTRIB_RELEASE" = "14.10" ]; then
            #   for isr in $drbl_common_root/etc/rcS.d/*; do
            #     [ "$isr" = "$drbl_common_root/etc/rcS.d/S00wait-drbl" ] && continue
            #     rm -f $isr
            #   done
            # fi
	  fi
	fi
	;;
    esac
  fi

  # Start for Linux Mint , by Ceasar
  if [ "$DISTRIB_ID" = "LinuxMint" -a -z "$(echo "$DISTRIB_DESCRIPTION" | grep -iE '^LMDE' )" ]; then
    case "$DISTRIB_RELEASE" in
      *)
        # LinuxMint "17"|"17.1"|"17.2") or later
        if [ -e "$drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/drbl-client-boot.conf" ]; then
          cp -af $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/drbl-client-boot.conf $drbl_common_root/etc/init/drbl-client-boot.conf
        else
          if ! is_systemd_init; then
            [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
            echo "Warning! Unable to find the fine-tune file $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/drbl-client-boot.conf, use $drbl_setup_path/files/${DISTRIB_ID}/drbl-client-boot-default.conf for DRBL clients!"
            echo "This may cause some problems to DRBL clients!"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
            cp -af $drbl_setup_path/files/${DISTRIB_ID}/drbl-client-boot-default.conf $drbl_common_root/etc/init/drbl-client-boot.conf
          fi
        fi

        if [ -e "$drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/S00wait-drbl" ]; then
          cp -af $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/S00wait-drbl $drbl_common_root/etc/rcS.d/
        else
          if ! is_systemd_init; then
            [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
            echo "Warning! Unable to find the fine-tune file $drbl_setup_path/files/${DISTRIB_ID}/$DISTRIB_RELEASE/S00wait-drbl, use $drbl_setup_path/files/${DISTRIB_ID}/S00wait-drbl-default for DRBL clients!"
            echo "This may cause some problems to DRBL clients!"
            [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
            cp -af $drbl_setup_path/files/${DISTRIB_ID}/S00wait-drbl-default $drbl_common_root/etc/init/S00wait-drbl
          fi
        fi
        # deal with plymouth.conf
        if [ -e "$drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/plymouth.conf" ]; then
          # Use the customized plymouth.conf.
          cp -af $drbl_setup_path/files/${DISTRIB_ID}/${DISTRIB_RELEASE}/plymouth.conf $drbl_common_root/etc/init/plymouth.conf
        else
          if [ "$DISTRIB_RELEASE" \< 17 ]; then
            echo "Not supported version: DISTRIB_ID='$DISTRIB_ID' ; DISTRIB_RELEASE='$DISTRIB_RELEASE'";
          elif [ "$DISTRIB_RELEASE" \< 18 ]; then
            # For : LinuxMint 17.x
            echo "manual" > $drbl_common_root/etc/init/plymouth.override
	    perl -pi -e 's|^([[:space:]]*)(status plymouth-shutdown.*start wait-for-state WAITER=rc WAIT_FOR=plymouth-shutdown.*)|$1true #$2 # Commented by DRBL to keep the services in rc in same console|g' $drbl_common_root/etc/init/rc.conf
	  else
            # For : LinuxMint 18 or later (pre-expected)
	    perl -pi -e 's|^([[:space:]]*)(status plymouth-shutdown.*start wait-for-state WAITER=rc WAIT_FOR=plymouth-shutdown.*)|$1true #$2 # Commented by DRBL to keep the services in rc in same console|g' $drbl_common_root/etc/init/rc.conf
	  fi
        fi
      ;;
      *)
        echo "Not supported version :$DISTRIB_ID <$DISTRIB_RELEASE>";
      ;;
    esac
  fi
  # End for LinuxMint

  # Modify upstart 0.6.3 /etc/init.d/*.conf.
  if [ -d "$drbl_common_root/etc/init" ]; then
    # For Ubuntu 9.10 upstart problem.
    # Ref: https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/405847
    # Change the contents of /etc/init/rc-sysinit.conf, since this rc-sysinit.conf file will be used for Clonezilla live and DRBL, in Clonezilla live we do not change the "start", but in DRBL we do. If we do not change it to be "drbl-client-boot", which is after "startup", the /sbin/init.orig will do nothing since in DRBL client, it's diskless, so no "filesystem".
    # start on .* -> start on startup.
    # For portmap.conf, one more extra line, i.e.:
    #start on (local-filesystems
    #          and net-device-up IFACE=lo)
    # upstart_conf_2_be_startup is for those conf will be "start on startup"
    # So the sequence:
    # 1st group: startup -> udev.conf and portmap.conf
    # 2nd group: drbl-client-boot (which contains virtual fs, dubs, hal, nfs...)
    # 3rd group: after drbl-client-boot -> rc-sysinit.conf
    # For Ubuntu 11.10, (1) Make mounted-var.conf start on startup since /var/run need to be linked to /run so it's writable for other daemons. (2) Commented dbus.conf since it will be started in drbl-client-boot.conf. Otherwise drbl-client-boot.conf will exit with error code.
    upstart_conf_2_be_startup="udev.conf rpcbind-boot.conf mounted-var.conf"
    upstart_conf_2_be_after_drbl_client_boot="rc-sysinit.conf"
    upstart_conf_2_be_manual="dbus.conf mountall.conf mountall-net.conf resolvconf.conf network-manager.conf isc-dhcp-server6.conf isc-dhcp-server.conf tftpd-hpa.conf"
    for i in $upstart_conf_2_be_startup; do
      if [ -e "$drbl_common_root/etc/init/$i" ]; then
        perl -pi -e "s/^start on.*/start on startup # Modified by DRBL/g" $drbl_common_root/etc/init/$i
      fi
    done
    for i in $upstart_conf_2_be_after_drbl_client_boot; do
      if [ -e "$drbl_common_root/etc/init/$i" ]; then
        perl -pi -e "s/^start on.*/start on startup and started drbl-client-boot # Modified by DRBL/g" $drbl_common_root/etc/init/$i
      fi
    done
    # Remove the extra one line "and net-device-up IFACE=lo)"
    if [ -e "$drbl_common_root/etc/init/portmap.conf" ]; then
      perl -pi -e "s/^[[:space:]]*and net-device-up IFACE=lo.*//g" $drbl_common_root/etc/init/portmap.conf
    fi
    for i in $upstart_conf_2_be_manual; do
      # Force to disable client's some services
      if [ -e "$drbl_common_root/etc/init/$i" ]; then
        switch_upstart_service "$drbl_common_root/etc/init/$i" off
      fi
    done
    # Disable the recovery-menu, use sulogin, otherwise the error messages of Clonezilla will be overwritten.
    if [ -e "$drbl_common_root/etc/init/rcS.conf" ]; then
      perl -pi -e "s|(^[[:space:]]*exec) /usr/share/recovery-mode/recovery-menu.*|\$1 /sbin/sulogin # Modified by DRBL. Force to use sulogin!|g" $drbl_common_root/etc/init/rcS.conf
      # We have to force to enter different runlevel, not in runlevel 1 , otherwise the Clonezilla job (/etc/rc1.d/S19ocs-run) will be run again.
      perl -pi -e "s|(^[[:space:]]*) start --no-wait rc-sysinit.*|\$1 telinit 2 # Modified by DRBL. Force to enter runlevel 2 to avoid clonezilla job is run again!|g" $drbl_common_root/etc/init/rcS.conf
    fi
  fi

elif [ -e /etc/SuSE-release ]; then
  # SuSE
  # 1. In SuSE, /etc/init.d/reboot is link to halt, so we just have to modify
  # halt.
  perl -pi -e 's|^(> /success.*)|#$1 # Modified by DRBL|' $drbl_common_root/etc/init.d/halt
  perl -pi -e 's|^(umount -anvt proc.*)|#$1 # Modified by DRBL|' $drbl_common_root/etc/init.d/halt
  perl -pi -e 's|^(test -z.*fuser -sk -HUP $hupon)|#$1 # Modified by DRBL|' $drbl_common_root/etc/init.d/halt
  # 2. Do not clean or remove etc/mtab when boots
  perl -pi -e 's|^([[:space:]]*)(rm -f /etc/mtab.*)|$1# $2 # Modified by DRBL|' $drbl_common_root/etc/init.d/boot.rootfsck
  # 3. For OpenSuSE 10.0, clean /fastboot in boot.localfs is:
  #	rm -f /etc/mtab* /etc/nologin /nologin /fastboot /forcefsck /success
  # Not only etc/mtab, do not remove /fastboot, either, keep it, since DRBL client is always fastboot
  perl -pi -e 's|^([[:space:]]*rm -f )/etc/mtab\* (.*)/fastboot(.*)|$1 $2 $3 # Modified by DRBL|' $drbl_common_root/etc/init.d/boot.localfs
  # It's not easy to write in one command, so for OpenSuSE 10.1, we add another line to clean /fastboot in /etc/init.d/boot.localfs:
  #	rm -f /etc/nologin /nologin /fastboot /forcefsck /success
  # Do not remove /fastboot, keep it, since DRBL client is always fastboot
  perl -pi -e 's|^([[:space:]]*rm -f .*)/fastboot(.*)|$1 $2 # Modified by DRBL|' $drbl_common_root/etc/init.d/boot.localfs
  # Do not umount -t tmpfs.
  perl -pi -e 's|umount -t tmpfs.*;;|continue ;; # Modified by DRBL|' $drbl_common_root/etc/init.d/boot.localfs
  # For OpenSuSE 11.3, the unmounting tmpfs part has changed. Modify here:
  perl -pi -e 's|^(typeset -r nomnt=autofs,.*)|$1,tmpfs # Modified by DRBL|' $drbl_common_root/etc/init.d/boot.localfs

  # 4. boot.rootfsck, we comment the mount -f / to avoid / be mounted twice.
  perl -pi -e 's|^([[:space:]]*)(mount -f /)|$1# $2 # Modified by DRBL|g' $drbl_common_root/etc/init.d/boot.rootfsck

  # 5. Force /etc/init.d/rc1.d/S*single to be at S90, not too early. In OpenSuSE 11.1, it's S10single, while ocs-run is S19.
  (
    if ls $drbl_common_root/etc/init.d/rc1.d/S*single >/dev/null 2>&1; then
      cd $drbl_common_root/etc/init.d/rc1.d/
      mv S*single S90single
    fi
  )
else
  # RH-like
  if [ -f "$drbl_setup_path/files/${OS_type}/${OS_Version}/halt.$OS_Version.drbl" ]; then
    cp -f $drbl_setup_path/files/${OS_type}/${OS_Version}/halt.$OS_Version.drbl $drbl_common_root/etc/init.d/halt
  else
    # not Debian, it's RH-like (BSD style), so show warning. This is only necessary for CentOS <= 6, since for Fedora, when >= version 17, no required. //NOTE// From drbl 2.x, only CentOS and Fedora are supported.
    OS_Version_Major="${OS_Version:0:3}"  # E.g. CO5.8 -> CO5
    case "$OS_Version" in
    CO*)
      if ! is_systemd_init; then
        most_related_ver="$(LC_ALL=C find $drbl_setup_path/files/$OS_type/${OS_Version_Major}* -type d -exec basename {} \; 2>/dev/null | sort | uniq | tail -n 1)"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
        echo "Warning! The fine-tune file ${drbl_setup_path}/files/${OS_type}/${OS_Version}/halt.${OS_Version}.drbl was not found. Using $drbl_setup_path/files/${OS_type}/${most_related_ver}/halt.${most_related_ver}.drbl as /etc/init.d/halt for DRBL clients!"
        echo "This may cause some problems to DRBL clients!"
        [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
        [ -n "$most_related_ver" ] && cp -f $drbl_setup_path/files/${OS_type}/${most_related_ver}/halt.${most_related_ver}.drbl $drbl_common_root/etc/init.d/halt
      fi
      ;;
    esac
  fi
  # From Fedora 9, upstart is used, and the post script of rc1 will force to terminate all programs after S19ocs-run is run in the end of rc1. i.e. when client finishes cloning in Clonezilla SE, a reboot or shutdown command (e.g. ocs-sr -p reboot...) will be killed by the post-stop script of rc1. Therefore we comment it.
  # The post script in /etc/event.d/rc1 is:
  #post-stop script
  #	clear
  #	TEXTDOMAIN=initscripts
  #	. /etc/profile.d/lang.sh
  #	echo $"Telling INIT to go to single user mode."
  #	exec telinit S
  #end script
  if [ -e "$drbl_common_root/etc/event.d/rc1" ]; then
    perl -pi -e 's|(^[[:space:]]*)(clear)|$1# $2 # Modified by DRBL|' $drbl_common_root/etc/event.d/rc1
    perl -pi -e 's|(^[[:space:]]*)(.*Telling INIT to go to single user mode.*)|$1# $2 # Modified by DRBL|' $drbl_common_root/etc/event.d/rc1
    perl -pi -e 's|(^[[:space:]]*)(exec telinit S)|$1# $2 # Modified by DRBL|' $drbl_common_root/etc/event.d/rc1
    # Instead, we put a modified single to be run after S19ocs-run
    cp -af $drbl_setup_path/files/RH/single.drbl $drbl_common_root/etc/rc1.d/S99single
  fi
fi

# delete the users in template, i.e. we will use the YP, not local account
# in clients
echo -n "Deleting the accounts (except root) in the clients common root template... "
usrdel_file_need="/usr/sbin/userdel"
cp --parents -d $usrdel_file_need $drbl_common_root
if ldd $usrdel_file_need &>/dev/null; then
  usrdel_lib_need=$(LC_ALL=C ldd /usr/sbin/userdel | sed -e "s/.*=> //g" -e "s/(0x.*)//g" | awk '{print $1}')
  for imod in $usrdel_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 $drbl_common_root
  done
fi
# UGLY... For SuSE, we need to copy /usr/lib/pwdutils/ to $drbl_common_root,
# but why ? Here it's just a lots of try-and-errors...
[ -d /usr/lib/pwdutils/ ] && cp --parents -d -r /usr/lib/pwdutils $drbl_common_root
[ -x /usr/sbin/userdel-pre.local ] && cp --parents -d /usr/sbin/userdel-pre.local $drbl_common_root
[ -x /usr/sbin/userdel-post.local ] && cp --parents -d /usr/sbin/userdel-post.local $drbl_common_root
# /usr/bin/crontab exists in /usr/sbin/userdel-pre.local in SuSE
[ -x /usr/bin/crontab ] && cp --parents -d /usr/bin/crontab $drbl_common_root

user_to_del="$(drbl-get-common-username 2>/dev/null)"
for u in $user_to_del; do
  if grep -q "^$u:" $drbl_common_root/etc/passwd; then
    chroot $drbl_common_root /usr/sbin/userdel $u 2>/dev/null
  fi
done
# We need nobody user. However, since some services are started before yp/nis, we will let nobody as local account. Comment this one.
#echo "Exporting nfsnobody in NIS/YP...".
#perl -pi -e "s/^.*NFSNOBODYUID=.*/NFSNOBODYUID=0/g" /var/yp/Makefile
#perl -pi -e "s/^.*NFSNOBODYGID=.*/NFSNOBODYGID=0/g" /var/yp/Makefile
# Oct/25/2011, for better security, do not show the hashed yp passwd. Thanks to Robert Arkiletian <robark _at_ gmail com> for reporting this issue.
perl -pi -e "s/^MERGE_PASSWD=.*/MERGE_PASSWD=false/g" /var/yp/Makefile
perl -pi -e "s/^MERGE_GROUP=.*/MERGE_GROUP=false/g" /var/yp/Makefile
# Enable "shadow" in "all line" in /var/yp/Makefile.
# For Fedora/CentOS, the "all line" is like:
# all:  passwd group hosts rpc services netid protocols mail \
#	# netgrp shadow publickey networks ethers bootparams printcap \
#	# amd.home auto.master auto.home auto.local passwd.adjunct \
#	# timezone locale netmasks
# For Debian/Ubuntu, it is like:
# ALL =   passwd group hosts rpc services netid protocols netgrp
# #ALL += publickey mail ethers bootparams printcap
# ##ALL += amd.home auto.master auto.home auto.local
# ##ALL += timezone locale networks netmasks
# #
# ## Autodetect /etc/shadow if it's there
# #ifneq ($(wildcard $(SHADOW)),)
# #ALL += shadow
# #endif
# #
# ## Autodetect /etc/passwd.adjunct if it's there
# #ifneq ($(wildcard $(ADJUNCT)),)
# #ALL += passwd.adjunct
# #endif
# #
# #all:   $(ALL)
if [ -z "$(LC_ALL=C grep -Ew "^all:.*shadow.*" /var/yp/Makefile)" ]; then
  perl -pi -e 's|(^all:)(.*)|$1 shadow $2|g' /var/yp/Makefile
fi
echo "done!"

# Enable the NIS client for this template
# For Mandrake/Debian, there is no authconfig,
# Mandrake use drakauth, but not interactive ?
echo -n "Enabling the NIS client in the common root template... "
# For RH-like, used to use /usr/sbin/authconfig, but in FC5, it's python... not easy to create the "create_authconfig_env $drbl_common_root/"
# turn on the nis in common root's /etc/nsswitch.conf, this is necessary for MDK/DBN since MDK/DBN does NOT have /usr/sbin/authconfig
perl -pi -e "s/^passwd:.*/passwd:     files nis/" $drbl_common_root/etc/nsswitch.conf
perl -pi -e "s/^shadow:.*/shadow:     files nis/" $drbl_common_root/etc/nsswitch.conf
perl -pi -e "s/^group:.*/group:     files nis/" $drbl_common_root/etc/nsswitch.conf
perl -pi -e "s/^hosts:.*/hosts:     files nis dns/" $drbl_common_root/etc/nsswitch.conf

# Patch for mandriva, e.g. 2009 or 2010, the /etc/init.d/sound is using /root/tmp/ as the temp dir. This will make /etc/init.d/sound not work in client because it's early before NFS /root is mounted. We have filed a bug report in https://qa.mandriva.com/show_bug.cgi?id=55929 to suggest to use /tmp/ instead of /root/tmp/.
if [ -e "$drbl_common_root/etc/init.d/sound" ]; then
  perl -pi -e 's|^([[:space:]]*)MIXER_SETTINGS=/root/tmp/asound.state_tmp|$1MIXER_SETTINGS=/tmp/asound.state_tmp|g' $drbl_common_root/etc/init.d/sound
fi

# For Debian
if [ -e /etc/debian_version ]; then
  if [ -f $drbl_common_root/etc/default/nis ]; then
    perl -p -i -e "s/^NISSERVER=.*/NISSERVER=false/" $drbl_common_root/etc/default/nis
    perl -p -i -e "s/^NISCLIENT=.*/NISCLIENT=true/" $drbl_common_root/etc/default/nis
  fi
fi
# Turn off wicd autostart, otherwise user need to enter password when entering XFCE in drbl client. It's not required because the network configuration on drbl client is done during booting.  This is especially for DRBL live.
if [ -e $drbl_common_root/etc/xdg/autostart/wicd-tray.desktop ]; then
  cat <<-WICD_END > $drbl_common_root/etc/xdg/autostart/wicd-tray.desktop
[Desktop Entry]
# Disabled by DRBL.
Hidden=true
WICD_END
fi
echo "done!"

echo -n "Creating some necessary files in the clients common root template..."
# set the arguments "-q" in kudzu to let system do configuration that
# doesn't require user input
if [ -d "$drbl_common_root/etc/sysconfig" -a "$drbl_common_root/etc/sysconfig/kudzu" ]; then
    if ! grep -qE "^KUDZU_ARGS=-q" $drbl_common_root/etc/sysconfig/kudzu 2>/dev/null; then
      echo "KUDZU_ARGS=-q" >> $drbl_common_root/etc/sysconfig/kudzu
    fi
fi

#echo -n "."
# write the ntp server setting
#if ! grep -q "^server pool.ntp.org" /etc/ntp.conf 2>/dev/null; then
#  echo "server pool.ntp.org" >> /etc/ntp.conf
#fi

# set the restrict for ntp clients
#if ! grep -q "^restrict default ignore" /etc/ntp.conf 2>/dev/null; then
#  echo "restrict default ignore" >> /etc/ntp.conf
#fi

#if ! grep -q "^restrict 127.0.0.1" /etc/ntp.conf 2>/dev/null; then
#  echo "restrict 127.0.0.1" >> /etc/ntp.conf
#fi

echo -n "."
# Create the /var in template, only directory
# Other directories in /var/lib/ are important for some applications.
# /var/lib/rpm/* is necessary for rpm database,
# /var/spool/mail is necessary for each user.
# It's better to export /var/lib all.

# Use rsync will be easier....Thanks to Wayne Davison wayned@samba.org
rsync -a $RSYNC_OPT_EXTRA --include="*/" --exclude="*" /var $drbl_common_root/

# symbolic_files_in_var_chklist is loaded in drbl.conf.
# On Ubuntu 11.10, FC17, /var/run is linked to /run, and /var/lock is linked to /run/lock.
# On Fedora 17, /var/run and /var/lock have to create as a link to "/run" and "/run/lock" before client booting. Have to use absolute not relative path

for i in $symbolic_files_in_var_chklist; do
  if [ -L /var/$i ]; then
    _tmp_absolute="$(readlink -f /var/$i)"
    rm -f $drbl_common_root/var/$i
    ln -s $_tmp_absolute $drbl_common_root/var/$i
  fi
done

echo -n "."

# For SuSE, we need to copy /var/X11R6 to clients also. How about /var/adm ?
[ -n "$(unalias ls 2>/dev/null; ls /var/X11R6/* 2>/dev/null)" ] && rsync -a $RSYNC_OPT_EXTRA /var/X11R6/* $drbl_common_root/var/X11R6/
# UGLY!
# /var/yp/nicknames is importand in clients, otherwise "ypcat passwd" won't work.
[ -e /var/yp/nicknames ] && cp -a /var/yp/nicknames $drbl_common_root/var/yp/

# Copy all /var/lib/* to the common root
# For /var/lib/, we can not use $RSYNC_OPT_EXTRA, since if we just run drblsrv
# some files, like in /var/lib/rpm/, it's newer than those in the system.
# We force to sync that in the server to client.
# varlib_NOT_2_be_copied_2_common_root is loaded from drbl.conf
# prepare the options for rsync to exclude when copy files in
# /var/lib/* to /tftpboot/node_root/var/lib/
varlib_opts_common_to_common=""
for iv in $varlib_NOT_2_be_copied_2_common_root; do
  varlib_opts_common_to_common="$varlib_opts_common_to_common --exclude=$iv/ "
done
[ -d /var/lib ] && rsync -a $varlib_opts_common_to_common /var/lib/* $drbl_common_root/var/lib/

# Copy selected /var/cache/* to the common root
for icache in $varcache_2_be_copied_2_common_root; do
  [ -d "/var/cache/$icache" ] && rsync -a $RSYNC_OPT_EXTRA /var/cache/$icache $drbl_common_root/var/cache/
done

# In OpenSUSE 10.1, if "/var/log/lastlog" does NOT exist in client, pam_lastlog will refuse to run, and user or root won't be able to login in client's console.
# The error in client will be like:
# May 20 06:40:48 opensuse101102 login[2996]: pam_lastlog(login:session): unable to open /var/log/lastlog: No such file or directory
touch $drbl_common_root/var/log/lastlog
# For OpenSuSE 10.1, if /var/lib/nfs/state does not exist, it will show err.
touch $drbl_common_root/var/lib/nfs/state
# For Debian 4.0, if /var/log/dmesg does not exist, it will complain when first boot.
touch $drbl_common_root/var/log/dmesg

};

# print all the nfsserver to $drbl_common_root/etc/diskless-image/config
print NFSSERVER_OUT "NFSSERVER_LIST=\"";
foreach my $k1 ( sort(keys %$rHoH) ) {
  if( $k1=~/general/ ) { next; } # skip general block
  my $nfsserver=$rHoH->{$k1}{"NFSSERVER"};
  #---------------
  my $interface=$rHoH->{$k1}{"INTERFACE"};
  # Try to get setting from system also
  # use the NIC "eth1, eth2..." of DRBL server as default nfsserver_sys...
  my $nfsserver_sys;
  chomp($nfsserver_sys=`drbl-get-ipadd $interface`);
  # set nfsserver, the priority: use the config file first, if unset, then use the value in system
  if ( ! $nfsserver ) {
   $nfsserver = $nfsserver_sys;
   print "* nfsserver is not set in config file, \nthe one \"$nfsserver\" got from system will be used.\n" if $verbosity >= 2;
  }

  # check if the values are set in config file or system
  unless ( $nfsserver ) {
     print "Error! NFSSERVER is unset!\n";
     print "Please set nfsserver in config file \"$_[0]\" or IPADDR in system config file.\n";
     exit;
  }
    #---------------
    #print "nfsserver: $nfsserver\n";
    print NFSSERVER_OUT "$nfsserver ";

    # next one
    $i++;
  };
print NFSSERVER_OUT "\"\n";

print DISKLESS_OUT q{
echo -n ". "
# append all the nfsserver to $drbl_common_root/etc/diskless-image/config
cat nfsserver_all >> $drbl_common_root/etc/diskless-image/config

echo "done!"
};

# Part 3,
# create every client node, like Debian's diskless-newhost
#
  print DISKLESS_OUT q{
# create every client node, like Debian's diskless-newhost
};

  foreach my $k1 ( sort(keys %$rHoH) ) {
    if( $k1=~/general/ ) { next; } # skip general block
    my $interface=$rHoH->{$k1}{"INTERFACE"};
    my $network=$rHoH->{$k1}{"NETWORK"};
    my $nfsserver=$rHoH->{$k1}{"NFSSERVER"};
    my $bootserver=$rHoH->{$k1}{"BOOTSERVER"};
    my $nisserver=$rHoH->{$k1}{"NISSERVER"};
    my $gateway=$rHoH->{$k1}{"GATEWAY"};
    my $nbi=$rHoH->{$k1}{"NBI"};
    my $mac=$rHoH->{$k1}{"MAC"};
    my $ip_start=$rHoH->{$k1}{"IP_START"};
    my $range=$rHoH->{$k1}{"RANGE"};

    if( length($bootserver)==0 ) { $bootserver=$nfsserver; }
    if( length($nisserver)==0 ) { $nisserver=$nfsserver; }
    if( length($gateway)==0 ) { $gateway=$nfsserver; }
    if( length($nbi)==0 ) { $nbi=$rHoH->{"general"}{"NBI"}; }
    # Try to get setting from system also
    # use the NIC "eth1, eth2..." of DRBL server as default nfsserver_sys...
    chomp($hostname_sys=`hostname`);
    chomp($netmask_sys=`drbl-get-netmask $interface`);
    chomp($ipaddr_sys=`drbl-get-ipadd $interface`);
    # the IP address for server is the NFS server for client
    my $nfsserver_sys=$ipaddr_sys;
    my $bootserver_sys=$nfsserver_sys;
    my $nisserver_sys=$nfsserver_sys;
    # set nfsserver, bootserver, nisserver address, the priority: use the config file first, if unset, then use the value in system

    # If hostname_prefix unset, try to set it as that of server
    if ( ! $hostname_prefix ) {
      @hostname_sp_sys=split(/\./,$hostname_sys);
      $hostname_prefix="$hostname_sp_sys[0]";
    }

    unless ( $netmask_sys ) {
       print "Error! NETMASK is unset!\n";
       print "Please set NETMASK in system config file.\n";
       exit;
    }

    if ( ! $network ) {
      # Since there are two versions of ipcalc, we use the perl one, which is
      # from http://jodies.de/ipcalc
      $network = `drbl-ipcalc $ipaddr_sys $netmask_sys | awk -F' ' '/Network:/ {print \$2}' | sed -e "s|/.*||g"`;
      chomp($network);
      print colored ("The calculated NETWORK for $interface is $network.\n", "$color_warn");
    }

    if ( ! $hostname ) {
     $hostname = $hostname_sys;
     print "* hostname is not set in config file, \nthe one \"$hostname\" got from system will be used.\n" if $verbosity >= 2;
    }

    if ( ! $nfsserver ) {
     $nfsserver = $nfsserver_sys;
     print "* nfsserver is not set in config file, \nthe one \"$nfsserver\" got from system will be used.\n" if $verbosity >= 2;
    }
    if ( ! $bootserver ) {
     $bootserver = $bootserver_sys;
     print "* bootserver is not set in config file, \nthe one \"$bootserver\" got from system will be used.\n" if $verbosity >= 2;
    }
    if ( ! $nisserver ) {
     $nisserver = $nisserver_sys;
     print "* nisserver is not set in config file, \nthe one \"$nisserver\" got from system will be used.\n" if $verbosity >= 2;
    }
    if ( ! $gateway ) {
     $gateway = $bootserver;
     print "* gateway is not set in config file, \nUse bootserver as gateway.\n" if $verbosity >= 2;
    }

    # Last check if the values are set in config file or system
    unless ( $hostname ) {
       print "Error! HOSTNAME is unset!\n";
       print "Please set hostname in config file \"$_[0]\" or HOSTNAME in system config file.\n";
       exit;
    }
    unless ( $nfsserver ) {
       print "Error! NFSSERVER is unset!\n";
       print "Please set nfsserver in config file \"$_[0]\"\n";
       exit;
    }
    unless ( $bootserver ) {
       print "Error! BOOTSERVER is unset!\n";
       print "Please set bootserver in config file \"$_[0]\"\n";
       exit;
    }
    unless ( $nisserver ) {
       print "Error! NISSERVER is unset!\n";
       print "Please set nisserver in config file \"$_[0]\"\n";
       exit;
    }
    unless ( $gateway ) {
       print "Error! GATEWAY is unset!\n";
       print "Please set gateway in config file \"$_[0]\"\n";
       exit;
    }

    # go
    @nfsserverIp=split(/\./,$nfsserver);
    @networkIp=split(/\./,$network);

    # For alias IP address, we need something like:
    # Ref: https://lists.isc.org/pipermail/dhcp-users/2010-September/012053.html
    #shared-network "some-identifier" {
    #   subnet 192.168.100.0 netmask 255.255.255.0 {
    #     option subnet-mask  255.255.255.0;
    #     option routers 192.168.100.254;
    #     next-server 192.168.100.254;
    #
    #     pool {
    #       range 192.168.100.1 192.168.100.3;
    #     }
    #   }
    #   subnet 192.168.120.0 netmask 255.255.255.0 {
    #   }
    #}
    if ( $interface =~ /eth[0-9]+:[0-9]+/ ) {
      print DHCPD_OUT <<EOF;
shared-network "alias-interface-identifier" {
EOF
    }

    print DHCPD_OUT <<EOF;
subnet $network netmask $netmask_sys {
    option subnet-mask	$netmask_sys;
    option routers $gateway;
    option rpi-tftp-server "$bootserver";
    next-server $bootserver;

EOF

    # range option, we have to create the IP table file
    chomp ( $iplist_tmp = `LC_ALL=C mktemp /tmp/drbl_iprange.XXXXXX` );
    print "interface: $interface\n" if $verbosity >= 2;
    if( length($mac)==0 && length($range)!=0 ) {
        # range case. The config shown in drblpush.conf:
        # range=1-15
	# so $rs=1, $re=15
        ($rs,$re)=split(/-/,$range,2);
        $total_count=$re-$rs+1;
        # get the initial value in the last set of digits in the IP address
        # from range starting no.
        $ip_start=$rs;
    } else {
        # MAC case. The config shown in drblpush.conf:
        # [eth1]
        # interface=eth1
        # mac=macadr-eth1.txt
        # ip_start=1
        chomp($total_count=`LC_ALL=C cat $mac | wc -l`);
    }
    chomp ($ip_hostmin=`LC_ALL=C drbl-ipcalc $ipaddr_sys $netmask_sys | awk -F' ' '/^HostMin:/ {print \$2}'`);
    # Here we add one more client, in case the IP address is used by server
    my $total_count_request=$total_count+1;
    # Todo: What if user assigns a wrong initial number (ip_start)?
    my @ip_tmp_sp=split(/\./,$ip_hostmin);
    my $ip_tmp_prefix="$ip_tmp_sp[0].$ip_tmp_sp[1].$ip_tmp_sp[2]";
    my $ip_tmp_start=$ip_tmp_prefix.".".$ip_start;

    # We should not let drbl-ipcalc-list to list 3 more IP addresses in case some of them are used, like in the server's ethernet port. Otherwise for class C, if user assigns total clients as 253, drbl-ipcalc-list won't be able to list 256 clients for class C (e.g. 192.168.1.0/24).
    system("drbl-ipcalc-list -c $total_count_request $ip_tmp_start $netmask_sys > $iplist_tmp");
    # Check if any IP address in the output file.
    my $ip_tmp_no="";
    chomp($ip_tmp_no=`LC_ALL=C wc -l $iplist_tmp | awk -F" " '{print \$1}'`);
    if ($ip_tmp_no eq "0" ) {
      print "Wrong configuration for this network card: $interface\n";
      print "$lang_deploy{\"program_stop\"}\n";
      exit (1);
    }

    # Remove the nfsserver IP address.
    system("perl -pi -e \"s/\\b$nfsserver\\b\\n//g\" $iplist_tmp");
    # Keep exact lines because drbl-ipcalc-list will output extra 3 lines
    system("LC_ALL=C head -n \"$total_count\" $iplist_tmp > $iplist_tmp.swap");
    system("cp -a $iplist_tmp.swap $iplist_tmp");
    unlink ("$iplist_tmp.swap") if -f "$iplist_tmp.swap";

    # Write the output shell script drbl_deploy.sh
    # Start with index = 1
    $i=1;
    while($i <= $total_count) {
      chomp ($ip=`perl -ne "$i..$i and print" $iplist_tmp`);
      print "IP address:$ip\n" if $verbosity >=2;

      # hostname for client
      # The default name will like fc192-168-0-1, fc10-0-0-1...,
      # i.e. $prefix{IP Address//./-}
      # If the hostname is assigned in /etc/drbl/client-ip-hostname,
      # we will ust that.
      my $ip_shown = $ip;
      $ip_shown =~ s/\./-/g;
      $label_default=$hostname_prefix.$ip_shown;
      chomp($label_assigned=`LC_ALL=C get-assigned-hn-by-ip $ip`);
      if ($label_assigned) {
        $label=$label_assigned;
      }else{
        $label=$label_default;
      }
      print "label:$label\n" if $verbosity >=2;

      if( length($mac)!=0 ) {
	# MAC addresses list
        # generate dhcpd.conf
	# without nbi set in config file
        chomp (my $macadd=`perl -ne "$i..$i and print" $mac`);
        print DHCPD_OUT <<EOF;
    host $label {
        hardware ethernet  $macadd;
        fixed-address $ip;
	# option host-name "$label";
    }
EOF
      } elsif( length($range)!=0 ) {
	# range list
	# do nothing
        print "In range loop with line $i\n" if $verbosity >=2;
      }

      # generate netgroup
      print NETGROUP_OUT "($label,,) ";

      # generate $CLIENT_IP_HOSTNAME_LIST
      print CLIENT_HOST_IP_LIST_OUT "$ip $label\n";

      # append the hosts to hosts_list
      print HOSTS_LIST_OUT <<EOF;
$ip
EOF

#
      print DISKLESS_OUT q{
      # When none full drbl mode AND none full clonezilla mode, we turn on pseudo option
      [ "$clonezilla_mode" != "full_clonezilla_mode" -a "$drbl_mode" != "full_drbl_mode" ] && [ "$pseudo_flag" = "on" ] && pseudo_opt="-p"
      };
      print DISKLESS_OUT <<EOF;
      # $keep_old_files_flag is assigned in shell, not from perl.
      drbl-gen-client-files -l $language -h $ip -k \$keep_old_files_flag -n $nfsserver -a $label -i $nisserver \$pseudo_opt
      [ -z "\$template_client" ] && template_client="$ip"
EOF
      print DISKLESS_OUT q{
      pseudo_flag=on
      };
      # next one
      $i++;
      print "Process line $i\n" if $verbosity >=2;
    }

    # generate dhcpd.conf
    if( length($mac)!=0 ) { # mac - just close it
      print DHCPD_OUT "}\n";
    }
    elsif( length($range)!=0 ) { # range - generate range & filename
        # without nbi set in config file
	# HERE
        chomp(my $ipstart=`LC_ALL=C head -n 1 $iplist_tmp`);
        chomp(my $ipend=`LC_ALL=C tail -n 1 $iplist_tmp`);
        print DHCPD_OUT <<EOF;
    pool {
      # allow members of "DRBL-Client";
      range $ipstart $ipend;
    }
}

EOF
    }
    # Keep file as ref file for later use.
    system("cp -a $iplist_tmp clients-of-$nfsserver.txt");
    # Clean the temp IP addresses list file
    unlink ($iplist_tmp) if -f $iplist_tmp;

    if ( $interface =~ /eth[0-9]+:[0-9]+/ ) {
      my $main_nic = $interface;
      my $main_nic_ip;
      my $main_nic_netmask;
      my $main_nic_subnet;
      # find the main NIC, i.e. eth0:1 -> eth0
      $main_nic =~ s/:[0-9]+//g;
      chomp($main_nic_ip=`drbl-get-ipadd $main_nic`);
      chomp($main_nic_netmask=`drbl-get-netmask $main_nic`);
      chomp($main_nic_subnet=`LC_ALL=C drbl-ipcalc $main_nic_ip/$main_nic_netmask | grep -Ei "^Network:" | awk -F " " '{print \$2}' | sed -re "s|\/.*||g"`);
      print DHCPD_OUT <<EOF;
subnet $main_nic_subnet netmask $main_nic_netmask { }
}
EOF
    }
  }

#
print DISKLESS_OUT q{
# Generate the files for DRBL single system image SSI
# Create the tarball template for DRBL SSI mode or Clonezilla box mode.
if [ "$drbl_mode" = "drbl_ssi_mode" -o \
     "$clonezilla_mode" = "clonezilla_box_mode" ]; then
  echo "Template client for DRBL SSI, Clonezilla box mode or Clonezilla live client is $template_client"
  drbl-gen-ssi-files -n -t $template_client
fi

#
if [ "$run_drbl_ocs_live_prep" = "yes" ]; then
  if [ "$clonezilla_mode" = "clonezilla_live_mode" ]; then
    drbl_ocs_live_server_opt=""
    [ -n "$drbl_ocs_live_server" ] && drbl_ocs_live_server_opt="-s $drbl_ocs_live_server"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo 'Preparing the system to use clonezilla live as the OS of clients...'
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    drbl-ocs-live-prep -b $live_client_branch -a $live_client_cpu_mode $drbl_ocs_live_server_opt
  else
    # Clean the previous Clonezilla live configuration.
    drbl-ocs-live-prep -u
  fi
fi

# output dhcpd arguments or interfaces to sysconfig file
dhcp_eths="$(awk -F"=" '/^interface=.*/ {print $2}' $config_file)"
# if the itnerface is alias, print the original interface
# i.e. if eth0:1, we print eth0
dhcp_eths="$(echo $dhcp_eths | sed -e "s/:[0-9]*//g")"
if [ -e "/etc/debian_version" ]; then
   # Debian, use the parameter "INTERFACESv4"
   echo "INTERFACESv4=\"$dhcp_eths\"" > $SYSCONF_PATH/$DHCP_SRV_NAME
elif [ -e "/etc/SuSE-release" ]; then
   perl -pi -e "s/^[#]*[[:space:]]*[#]*DHCPD_INTERFACE=.*/DHCPD_INTERFACE=\"$dhcp_eths\"/g" $SYSCONF_PATH/$DHCP_SRV_NAME
else
   # RH-like, use the parameter "DHCPDARGS"
   echo "# //NOTE from DRBL// This file is not used by Fedora/CentOS which uses systemd. This is only for older versions. However, we still need this for the function get_dhcpd_interface in drbl-functions" > $SYSCONF_PATH/$DHCP_SRV_NAME
   echo "DHCPDARGS=\"$dhcp_eths\"" >> $SYSCONF_PATH/$DHCP_SRV_NAME
fi

# turn on pxelinux passwd if set
if [ -n "$client_pxelinux_passwd" ]; then
  drbl-pxelinux-passwd -e --stdin $client_pxelinux_passwd
else
  drbl-pxelinux-passwd --disable
fi

# write the NISDOMAIN to system config file in DRBL server
NET_sys_RH="/etc/sysconfig/network"
NIS_Debian="/etc/defaultdomain"
NIS_SuSE="/etc/defaultdomain"
if [ -e /etc/debian_version ]; then
  echo "$nisdomain" > $NIS_Debian
  perl -p -i -e "s/^NISSERVER=.*/NISSERVER=master/" /etc/default/nis
  perl -p -i -e "s/^NISCLIENT=.*/NISCLIENT=true/"   /etc/default/nis
elif [ -e /etc/SuSE-release ]; then
  # SuSE
  echo "$nisdomain" > $NIS_SuSE
else
  # RH-like
  NIS_sys=$(grep NISDOMAIN $NET_sys_RH 2>/dev/null)
  if [ -z "$NIS_sys" ]; then
    echo "NISDOMAIN=$nisdomain" >> $NET_sys_RH
  else
    perl -p -i -e "s/^NISDOMAIN=.*/NISDOMAIN=$nisdomain/" $NET_sys_RH
  fi
fi

# before restart NIS, force the variable NISDOMAIN now is that set in config file
nisdomainname $nisdomain

# Since we set tcp as the default NFS protocol, if tcp over NFS is not supported in the server running kernel, make a switch for client to use udp.
# Ex:for RH9, tcp over NFS is not supported in the runnking kernel 2.4.20-8
if [ "$nfs_protocol" = "udp" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo 'Switch "tcp over NFS" to "udp over NFS" for the DRBL clients...'
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  drbl-nfs-conf --no-gen-ssi --protocol udp
fi

[ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
echo "Now add necessary services to this DRBL server: DHCP, TFTP, NFS, NIS..."
[ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL

# set the restrict in ntp.conf, only the subnet of DRBL clients can access.
#drbl_subnet=
#for ihost in /tftpboot/nodes/*; do
#  ip="`basename $ihost`"
#  subnet=$(echo $ip | cut -d"." -f1-3)
#  if [ -z "$(echo $drbl_subnet | grep $subnet 2> /dev/null)" ]; then
#    drbl_subnet="$drbl_subnet $subnet"
#  fi
#done
#for i_subnet in $drbl_subnet; do
#  if ! grep -q "^restrict $i_subnet.*" /etc/ntp.conf ; then
#    echo "restrict $i_subnet.0 mask 255.255.255.0 notrust nomodify notrap" >> /etc/ntp.conf
#  fi
#done

# create NFS exports
drbl-nfs-exports --no-restart generate

# start the iptables NAT
case "$drbl_server_as_NAT_server" in
  n|N|[nN][oO])
     [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
     echo "$msg_drbl_server_is_NOT_NAT_server"
     [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
     drbl-nat-rules clean ;;
  *)
     drbl-nat-rules generate ;;
esac

# set the YP securenets
drbl-yp-securenets --no-restart generate

# add drbl-clients-nat service for Debian DRBL server. This is only for Debian and Ubuntu.
if [ -e /etc/debian_version ]; then
  if is_systemd_init; then
    cp -f $drbl_setup_path/files/misc/drbl-clients-nat /etc/init.d
    cp -f $drbl_setup_path/files/misc/systemd/drbl-clients-nat.service /lib/systemd/system/
    systemctl enable /lib/systemd/system/drbl-clients-nat.service
  else
    cp -f $drbl_setup_path/files/misc/drbl-clients-nat /etc/init.d
    # before we do it, clean it to avoid the stalled files.
    if [ "$dbn_ubn_serv_control_prog" = "use-insserv" ]; then
      insserv -f -r drbl-clients-nat &>/dev/null
    else
      update-rc.d -f drbl-clients-nat remove &>/dev/null
      # It will be added to rcX.d by "drbl-all-service add", so we do not add it here
    fi
  fi
fi

# flush the YP
echo "Update YP..."
if [ -e /etc/debian_version ]; then
  # For Debian woody, it seems that /etc/networks is not automaticaly created.
  # If we can not find it, just touch it
  [ ! -e /etc/networks ] && touch /etc/networks
fi
# The hostname for the master is stored within each NIS map and so if you do not regenerate the maps the master returned will not change.
# Ref: http://www.usenetlinux.com/archive/topic.php/t-224905.html
# We need to update hosts.byname, hosts.byaddr...
[ -e /var/yp/Makefile ] && touch /var/yp/Makefile
# For FC17, it seems it won't work with "all" in the beginning. Therefore we addd the command without all.
make -C /var/yp &> /dev/null
make -C /var/yp all &> /dev/null

# Clean those pseudo clients (empty directories)
rmdir $drblroot/* 2>/dev/null

# reset some stale status, maybe drblpush is run again.
if [ -e "$ocs_lock_dir/clonezilla.lock" ]; then
  if type drbl-ocs &>/dev/null; then
    echo -n "Your system is already in clonezilla mode... we will stop the stale status... "
    drbl-ocs -n -l 0 stop &>/dev/null
    echo "done!"
  fi
fi

# add and (re)start all the service which DRBL server need.
# drbl-all-service will automatically add them to rcX.d before start them .
if [ "$add_start_drbl_services_after_cfg" != "no" ]; then
  drbl-all-service start
  retv=$?
  if [ "$retv" -gt 0 ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo "$msg_something_went_wrong_when_start_drbl_related_srv"
    echo "$msg_you_can_try_to_run_the_following_again:"
    echo "drbl-all-service start"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  fi
else
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo $msg_drbl_related_services_not_added_started
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

#
if [ "$use_existing_dhcp_srv" = "yes" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Use existing DHCP service, so now enable proxy DHCP mode..."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  # This will use one program, i.e., dnsmasq proxy mode for dhcp+tftp.
  drbl-proxy-dhcp enable
else
  # This will use two programs, i.e., ISC dhcpd + tftpd.
  # No issue about dnsmasq proxy mode.
  # Ref: ocs-live-feed-img, check comments about "A workaround to fix the dnsmasq issue"
  # Hence we can try to enable uEFI network secure boot for clients if it is assigned to enable.
  if [ "$secure_boot_client" = "yes" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Not using existing DHCP service, so try to enable uEFI secure boot service for clients..."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    drbl-gen-grub-efi-nb -s
  fi
fi

# set the boot prompt for clients if set
case "$set_client_system_select" in
   y|Y|[yY][eE][sS])
     # process if we wan to turn on/off the thin client option in PXE boot menu
     case "$open_thin_client_option" in
         y|Y|[yY][eE][sS])
	    # set the option for processing PXE boot menu
	    client_select_opt="-e"
	    # Turn on the thin client server (gdm/kdm...)
	    drbl-powerful-thin-client --no-gen-ssi --thin -ln $language
	    ;;
         n|N|[nN][oO])
	    # set the option for processing PXE boot menu
	    client_select_opt="-d"
	    # Turn on the thin client server (gdm/kdm...)
	    drbl-powerful-thin-client --no-gen-ssi --powerful -ln $language
	    ;;
     esac
     drbl-client-system-select $client_select_opt -t $client_system_boot_timeout on
     ;;
   n|N|[nN][oO])
     drbl-client-system-select off
     ;;
esac
# set graphic/text pxe boot menu for clients
case "$use_graphic_pxelinux_menu" in
   y|Y|[yY][eE][sS])
     switch-pxe-bg-mode -m graphic
     ;;
   n|N|[nN][oO])
     switch-pxe-bg-mode -m text
     ;;
esac

# if drbl_mode is none, disable drbl in pxelinux menu, and set default as local
if [ "$drbl_mode" = "none" ]; then
  # disable the DRBL in pxelinux menu
  hide_reveal_pxe_img drbl hide $pxecfg_pd/pxelinux.cfg/default
  # set local as default
  set-default-pxe-img -i local -c $pxecfg_pd/pxelinux.cfg/default
fi

# Force to update the pxelinux config
case "$drbl_mode" in
  "full_drbl_mode") drbl_mode_opt="-d 0" ;;
  "drbl_ssi_mode")  drbl_mode_opt="-d 1" ;;
  "none")           drbl_mode_opt="-d 2" ;;
esac
case "$clonezilla_mode" in
  "full_clonezilla_mode") clonezilla_mode_opt="-z 0" ;;
  "clonezilla_box_mode")  clonezilla_mode_opt="-z 1" ;;
  "none")                 clonezilla_mode_opt="-z 2" ;;
  "clonezilla_live_mode") clonezilla_mode_opt="-z 3" ;;
esac
tune-clientdir-opt -l $language --no-create-ssi-template $drbl_mode_opt $clonezilla_mode_opt

#
case "$purge_client" in
   n|N|[nN][oO])
     # Do not prompt user to restart client if no existing client exists
     tune_DBN_audio_plugdev_extra_opt="-r"
     ;;
esac
# set the DBN clients audio and plugdev if set
if [ -e /etc/debian_version ]; then
  case "$set_DBN_client_audio_plugdev" in
     y|Y|[yY][eE][sS])
       tune-debian-dev-group-perm -l $language -g "$desktop_user_group_debian" -e $tune_DBN_audio_plugdev_extra_opt
       ;;
  esac
fi

# post run
if [ -n "$(unalias ls 2>/dev/null; ls $DRBLPUSH_POSTRUN_DIR/ 2>/dev/null)" ]; then
  echo "Some files are found in $DRBLPUSH_POSTRUN_DIR. Run them now..."
  drbl-run-parts $DRBLPUSH_POSTRUN_DIR
fi

#
# echo warning message if TCPwrapper is set.
host_allow_set=$(grep -v "^[[:space:]]*#" /etc/hosts.allow 2>/dev/null)
host_deny_set=$(grep -v "^[[:space:]]*#" /etc/hosts.deny 2>/dev/null)
if [ -n "$host_allow_set" -o -n "$host_deny_set" ]; then
   client_ips="$(get-client-ip-list)"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "$msg_hosts_allow_deny_is_set"
   echo "$msg_you_must_make_sure_these_clients"
   # format the output, 4 IP addresses in one line
   # --------------------
   i=0
   for ip in $client_ips; do
    i=$(($i+1))
    echo -n "$ip "
    [ "$(expr $i % 4)" -eq 0 ] && echo
   done
   echo
   # --------------------
   echo "$msg_can_access_this_DRBL_server"
   echo "$msg_otherwise_client_fail_to_boot"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "TFTP open timeout"
   echo "TFTP......."
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
   echo "$msg_or"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
   echo "mount: RPC: Unable to receive; errno = Connection refused"
   [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

# Check the NFSD no, it's very important when heavy client traffic.
RUNNING_NFSDCOUNT="$(ps -ef | grep nfsd | grep -v grep | wc -l)"
total_necessary_nfsd="$(get-necessary-nfsd-no)"
if [ -z "$total_necessary_nfsd" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Warning! Unable to get the total necessary NFS daemon number!!!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi
if [ "$RUNNING_NFSDCOUNT" -lt "$total_necessary_nfsd" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "The number of running NFS services in this DRBL number ($RUNNING_NFSDCOUNT) is not enough for clients, $total_necessary_nfsd nsfd is expected! The performance will NOT be good! Check the NFS setting in /etc/sysconfig/ or /etc/default/!!!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi

#
#echo "$msg_delimiter_star_line"
#echo "Now syncing - flush filesystem buffers..."
sync;sync;sync
#
export LC_ALL=$LC_ALL_org

echo "$msg_delimiter_star_line"
echo "Enjoy DRBL!!!"
echo "http://drbl.org; http://drbl.nchc.org.tw"
echo "NCHC Free Software Labs, Taiwan. http://free.nchc.org.tw"
echo "$msg_delimiter_star_line"

# ask user to reboot after first time upgrade the nfs-utils in
# drblsrv_desktop.sh or get_drbl_kernel.sh
# if not, user will see a lot of
# "kernel: lockd: rejected NSM callback from 7f000001:1027"
# in the server console and /var/log/messages in some Linux (RH8 ?).
echo "$msg_if_you_like_you_can_reboot_to_make_sure_everthing"
echo "$msg_delimiter_star_line"
if [ "$add_start_drbl_services_after_cfg" != "no" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_drbl_server_is_ready $msg_all_set_you_can_turn_on_clients"
  #echo "$msg_note! $msg_etherboot_5_4_is_required"
  echo "$msg_run_drblpush_with_config_again"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
else
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo $msg_drbl_related_services_not_added_started
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
fi
};

  print NETGROUP_OUT "\n";
  print NETGROUP_OUT "# Added by DRBL, end\n";
  print CLIENT_HOST_IP_LIST_OUT "# Created by DRBL (drblpush), end\n";

  close(DHCPD_OUT);
  close(NETGROUP_OUT);
  close(CLIENT_HOST_IP_LIST_OUT);
  close(DISKLESS_OUT);
  close(NFSSERVER_OUT);
  close(HOSTS_LIST_OUT);
  close(SWAPCONF_OUT);
  #chnage its mode
  system("LC_ALL=C chmod 700 $main_sh");

  # set public IP if options is yes
  if ("$set_client_public_ip_opt" eq "yes" && "$mode" eq "create_config_file"){
       # then user run drblpush with -i, create the $public_ip_list
       print "$delimiter{\"star_line\"}\n".
             "$lang_deploy{\"ok_let_do_it\"}\n".
             "$delimiter{\"dash_line\"}\n";
       # create the $public_ip_list file
       set_client_public_ip("$hosts_list","$public_ip_list");
  }

} # end of the drbl_server_parse

#
sub check_MAC_file{
  my $macfile_dir="$_[0]";
  my $macfile_prefix="$_[1]";
  # note! maybe there are multiple MAC files when run drblpush with "-c"
  my $macfile_exist=system("LC_ALL=C ls $macfile_dir/$macfile_prefix* >/dev/null 2>&1");
  if ($macfile_exist == 256) {
    # unable to find the $macfile_prefix*
    print "$delimiter{\"star_line\"}\n".
          colored ("$lang_word{\"unable_to_find_the\"} $macfile_dir/$macfile_prefix; $lang_deploy{\"hint_for_detect_MAC\"} $macfile_prefix\n", "$color_warn").
          "$lang_deploy{\"press_enter_to_continue\"}";
          chomp($line=<STDIN>);
    print "$delimiter{\"dash_line\"}\n";
  }else{
   # MAC file exists, check if it contains illegal character.
   # empty those comment line, and delete the empty line and those comment line
   system("perl -p -i -e \"s/^[[:space:]]*#.*\$//g\" $macfile_dir/$macfile_prefix*");
   system("perl -p -i -e \"s/^[[:space:]]*\$//g\" $macfile_dir/$macfile_prefix*");
   my $macfile_check=`for ifile in $macfile_dir/$macfile_prefix*; do grep -v -E '([[:alnum:]]|:|^[[:space:]]*\$)' \$ifile; done`;
   chomp($macfile_check);
   if ( $macfile_check ) {
      print "$lang_deploy{\"illegal_char_in_MAC\"},".
            colored ("\"$macfile_check\"\n", "$color_fail").
            "$lang_deploy{\"fix_wrong_MAC_file\"} \n".
            "$lang_word{\"program_stop\"}!!!\n";
      exit(1);
   }
  }
} # end of check_MAC_file

#########################################
# Main program
my $no_deploy = 0;
my $config_file = "";
our $verbosity = 1;
# NOTE!!! Remember to update the usage_details also.
our $usage="Usage: $0 [-c|--config config_file] [-d|--debug] [-e|--accept-one-nic] [-h|--help] [-i|--interactive] [-k|--keep_clients Y/n] [-l|--language index_number] [-m|--client_startup_mode 1/2] [-n|--no_deploy] [-o|--clonezilla_home DIR] [-p|--port_client_no number] [-q|--quiet] [-r|--drbl_mode 0|1|2] [-t|--live_client_branch 0|1|2|3] [-s|--swap_create y/N] [-v|--verbose] [-z|--clonezilla_mode 0|1|2|3] [--skip-drbl-ocs-live-prep] [--drbl-ocs-live-server IP]";
sub usage_details{
  die "$usage\n".
  "-b, --not-add-start-drbl-srvi Do NOT add and start DRBL related services after the configuration is done\n".
  "-c, --config      The DRBL config file, text format\n".
  "-d, --debug       Turn on debug mode when run shell script\n".
  "-e, --accept-one-nic   Accept to run DRBL service on only one network card. ///NOTE/// This might mess up your network environment especially if there is an existing DHCP service in your local network environment.\n".
  "-h, --help        Show this help message\n".
  "-i, --interactive Interactive mode, setup step by step.\n".
  "-k, --keep_clients Y/n Keep previously saved files for clients.\n".
  "-m, --client_startup_mode [1|2] Assign client mode, 1 for graphic mode, 2 for text mode.\n".
  "-n, --no_deploy   Just create files, do NOT deploy the files into system\n".
  "-o, --clonezilla_home DIR  Use DIR as the Clonezilla image directory\n".
  "-p, --port_client_no number The client no. in each NIC port.\n".
  "-q, --quiet             Be less verbose\n".
  "-r, --drbl_mode [0|1|2] Assign DRBL mode (0: Full DRBL mode, 1: DRBL SSI mode, 2: Do NOT provide diskless Linux service to clients)\n".
  "-s, --swap_create y/N   Switch to create and use local swap in clients (yes or no)\n".
  "-t, --live_client_branch [0|1|2|3] Assign the Clonezilla live release branch to be used, 0 is stable branch (Debian-based), 1 is testing branch (Debian-based), 2 is alternative stable branch (Ubuntu-based), 3 is alternative testing branch (Ubuntu-based). This option should be used when -z|--clonezilla_mode = 3\n".
  "-u, --live_client_cpu_mode [0|1|2]  Assign the CPU mode for client when doing Clonezilla job with Clonezilla live (0: i586, 1: i686, 2: amd64)\n".
  "-v, --verbose           Be more verbose\n".
  "-z, --clonezilla_mode [0|1|2|3] Assign Clonezilla mode (0: Full DRBL mode, 1: Clonezilla box mode, 2: Do NOT provide Clonezilla service to clients, 3: Use Clonezilla live as the OS of clients)\n".
  "--skip-drbl-ocs-live-prep  Force to skip running drbl-ocs-live-prep\n".
  "--drbl-ocs-live-server IP  Assign the Clonezilla live server as IP when running drbl-ocs-live-prep\n".
  "-l, --language INDEX  Set the language to be shown (deprecated! Use environmental LC_ALL or LANG instead).\n".
  "                      [0]: English\n".
  "                      [1]: Traditional Chinese (Big5) - Taiwan\n".
  "                      [2]: Traditional Chinese (UTF-8, Unicode) - Taiwan\n".
  "                      [a|ask]: Prompt to ask the language index\n".
  "--ln INDEX            Set the language to be shown (deprecated! Use environmental LC_ALL or LANG instead).\n".
  "                      [en_US]: English\n".
  "                      [zh_TW.BIG5]: Traditional Chinese (Big5) - Taiwan\n".
  "                      [zh_TW.UTF-8]: Traditional Chinese (UTF-8, Unicode) - Taiwan\n".
      "";
} # end of usage_details

# Must have argument
die "$usage\n" if $#ARGV<0;

# Parse command-line options
while ($#ARGV != -1) {
   my $arg;
   $arg = shift(@ARGV);
   if (lc($arg) =~ /^(-)?(-)?l(anguage)?$/) {
     $lang_opt = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?ln$/) {
     $language = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?n(o_deploy)?$/) {
     $no_deploy = 1;
   } elsif (lc($arg) =~ /^(-)?(-)?c(config)?$/) {
     $config_file = shift(@ARGV);
     $mode="load_config_file";
   } elsif (lc($arg) =~ /^(-)?(-)?v(erbose)?$/) {
     $verbose_opt="-v";
     $verbosity++;
   } elsif (lc($arg) =~ /^(-)?(-)?q(uiet)?$/) {
     $verbosity--;
   } elsif (lc($arg) =~ /^(-)?(-)?p(ort_client_no)?$/) {
     $assign_client_no_each_port = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?h(elp)?$/) {
     usage_details();
   } elsif (lc($arg) =~ /^(-)?(-)?i(nteractive)?$/) {
     $mode = "create_config_file";
   } elsif (lc($arg) =~ /^(-)?(-)?k(eep_clients)?$/) {
     $keep_client = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?m(ode)?$/) {
     $client_startup_mode = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?s(wap_mode)?$/) {
     $swap_create = shift(@ARGV);
   } elsif (lc($arg) =~ /^-z$|^--clonezilla_mode$/) {
     $clonezilla_mode = shift(@ARGV);
   } elsif (lc($arg) =~ /^-t$|^--live_client_branch$/) {
     $live_client_branch= shift(@ARGV);
   } elsif (lc($arg) =~ /^-u$|^--live_client_cpu_mode$/) {
     $live_client_cpu_mode = shift(@ARGV);
   } elsif (lc($arg) =~ /^-r$|^--drbl_mode$/) {
     $drbl_mode = shift(@ARGV);
   } elsif (lc($arg) =~ /^-o$|^--clonezilla_home$/) {
     $ocs_img_repo_dir = shift(@ARGV);
   } elsif (lc($arg) =~ /^-b$|^--not-add-start-drbl-srvi$/) {
     $add_start_drbl_services_after_cfg = "no";
   } elsif (lc($arg) =~ /^-e$|^--accept-one-nic$/) {
     $continue_with_one_port = "yes";
   } elsif (lc($arg) =~ /^--skip-drbl-ocs-live-prep$/) {
     $run_drbl_ocs_live_prep = "no";
   } elsif (lc($arg) =~ /^--drbl-ocs-live-server$/) {
     $drbl_ocs_live_server = shift(@ARGV);
   } elsif (lc($arg) =~ /^(-)?(-)?d(ebug)?$/) {
     $sh_debug = "-x";
   } else {
     usage_details();
   }
}

# get the language
$language=lang_set($lang_opt) if ( ! $language );
require "$DRBL_SCRIPT_PATH/lang/perl/$language";

# hint for user to answer y/n
print "$delimiter{\"star_line\"}\n".
      colored ("$lang_deploy{\"hint_for_answer\"}\n", "$color_warn");

# check if drbl server package is installed or not
print "$delimiter{\"star_line\"}\n";
print "$lang_deploy{\"searching_installed_drbl_packages\"}\n";
# just pick package drbl to test

# return code is number divided by 256
my $drbl_rpm = system("LC_ALL=C rpm -q drbl > /dev/null 2>&1") / 256;
my $drbl_deb = system("LC_ALL=C dpkg -L drbl > /dev/null 2>&1") / 256;
my $drbl = $drbl_rpm * $drbl_deb;
if ($drbl eq 0) {
        print "$lang_deploy{\"finished_searching_installed_drbl_packages\"}\n";
	print "$delimiter{\"star_line\"}\n";
}else{
	print "$delimiter{\"star_line\"}\n".
	       colored ("$delimiter{\"warning_line\"}\n", "$color_warn").
	      "$lang_deploy{\"no_drbl_server_package_found\"}\n".
	      "[y/N] ";
	chomp($line=<STDIN>);
	SWITCH: for ($line) {
		/"^y"|"^yes"/i && do {
	          print "$delimiter{\"star_line\"}\n".
                        "$lang_deploy{\"ok_let_continue\"}\n".
                        "$lang_deploy{\"but_you_will_see_errors\"}\n";
                  last SWITCH;
                };
		/.*/ && do {
	          print "!!!!!!!!!!!!!!!!!!!!!!!!!\n".
                        "$lang_deploy{\"smart_decision\"}\n";
	          exit(1);
                  last SWITCH;
                };
        }
}

if ("$mode" eq "create_config_file") {
        print "$delimiter{\"dash_line\"}\n".
	      "$lang_deploy{\"interactive_mode_prompt\"}\n".
              "$delimiter{\"dash_line\"}\n";
        interactive_mode;
	$config_file=$DRBLPUSH_CONF;
} elsif ("$mode" eq "load_config_file") {
       # copy the pre-saved setting file to this working directory
       # config_file
       # 2 possibilities, $config_file is inputted as absolute or relative path.
       # (1) $config_file is inputted as absolute path, like /etc/drbl/drblpush.conf
       system("[ -f $config_file ] && cp -f $config_file .");
       # (2) If the $config_file is input as relative path, like ./drblpush.conf, we have to copy it from $orig_wd, since now it's in working dir.
       system("[ -f $orig_wd/$config_file ] && cp -f $orig_wd/$config_file .");
       # public IP setting
       system("[ -f $drbl_syscfg/$public_ip_list ] && cp -f $drbl_syscfg/$public_ip_list $public_ip_list");
       # MAC address files
       system("cp -f $drbl_syscfg/macadr-*.txt . > /dev/null 2>&1");

}
unless ( $config_file ) { die "$usage\n"; }

# parse the config file, then create the exe script file $main.sh
drbl_server_parse($config_file);

print "$delimiter{\"star_line\"}\n";
print "purge_client: $purge_client\n" if $verbosity >=2;
if ( $client_exist_flag = "0" && $purge_client eq "no" ) {
   # old clients exist and we want to keep them, show warning messages
   print colored ("$lang_deploy{\"note_for_keep_client_setting\"}\n", "$color_warn").
         "$lang_deploy{\"press_enter_to_continue\"}";
         chomp($line=<STDIN>);
}

# ready to go
if ( $no_deploy ) {
	print "$delimiter{\"warning_line\"}\n".
	      "$lang_deploy{\"no_deploy_prompt\"}\n";
}
else {
	print "$delimiter{\"star_line\"}\n".
	      "$lang_deploy{\"ready_to_deploy\"}\n".
	      colored ("$lang_deploy{\"overwrite_firewall_rule\"}\n", "$color_warn").
	      colored ("$lang_deploy{\"backup_firewall_rule\"}\n", "$color_warn").
	      "[Y/n] ";
	chomp($line=<STDIN>);
	if ($line eq "n" || $line eq "N" || $line eq "no" || $line eq "NO") {
	 print "$delimiter{\"exclamation_line\"}\n".
	       "$lang_deploy{\"oh_quit_now\"}\n";
         unlink ($main_sh) if -f $main_sh;
	} else {
	 print "$delimiter{\"star_line\"}\n".
               "$lang_deploy{\"ok_let_do_it\"}\n".
               "$delimiter{\"dash_line\"}\n";
         my $whoiam = `LC_ALL=C id -nu`;
	 chomp($whoiam);
         # Also copy the $DRBLPUSH_CONF to system so that we can re-run the
         # program by "drblpush -c $drbl_syscfg/$DRBLPUSH_CONF"
         my $run_main="LC_ALL=C ./$main_sh";
	 if ("$whoiam" eq "root") {
	     system("$run_main");
         }else{
             print "$lang_deploy{\"you_are_not_root\"},\n".
	           "$lang_word{\"please_enter\"} ". colored("$lang_word{\"root_passwd\"} ","$color_warn") ."$lang_word{\"to_deploy_them\"}...\n";
	     my $su_rlt=system("su -c '$run_main' root");
	     while ($su_rlt == 256) {
	            $su_rlt=system("su -c '$run_main' root");
	     }
	     # copy the config file to DRBL server
         }
        }
}
#
chdir ($orig_wd) || die ("Could not change to the original working directory!!!");
# clean the temp working directory
rmtree ($drblpush_wd) if -d $drblpush_wd;

#########################################