aboutsummaryrefslogtreecommitdiff
blob: 61ae53498696a8853dc62e0e8c3d51518f02eccc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
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
#!/bin/sh

call_func_timeout() {
	local func=$1 timeout=$2 pid watcher

	( ${func} ) & pid=$!
	( sleep ${timeout} && kill -HUP ${pid} ) 2>/dev/null & watcher=$!
	if wait ${pid} 2>/dev/null
	then
		kill -HUP ${watcher} 2>/dev/null
		wait ${watcher} 2>/dev/null
		return 0
	fi

	return 1
}

modules_load() {
	fn=${1}
	shift
	for module in $*
	do
		echo ${module} >> /etc/modules/${fn}
	done

	modules_scan ${fn}
}

modules_scan() {
	local MODS
	local loaded

	MODS=$(cat /etc/modules/${1} 2>/dev/null)
	[ -n "${MODS}" ] && [ -z "${QUIET}" ] && \
		printf "%b" "${BOLD}   ::${NORMAL} Loading from ${1}: "

	for x in ${MODS}
	do
		MLOAD=$(echo ${MLIST} | sed -e "s/.*${x}.*/${x}/")
		if [ "${MLOAD}" = "${x}" ] # Only module to no-load
		then
			[ -z "${QUIET}" ] && \
				printf "%b\n" "${BOLD}   ::${NORMAL} Skipping ${x} ..."
		elif [ "${MLOAD}" = "${MLIST}" ]
		then
			if [ "${ROOTFSTYPE}" != 'auto' ] && [ -b "${REAL_ROOT}" ]
			then
				echo "Root block device found, continuing ..."
				break
			fi

			if [ -n "${DEBUG}" ]
			then
				printf "%b" "${BOLD}   ::${NORMAL} "
				printf "%b" "Scanning for ${x} ..."
			fi

			modprobe ${x} >/dev/null 2>&1
			loaded=${?}

			[ -n "${DEBUG}" -a "${loaded}" = "0" ] && \
				echo "loaded"
			[ -n "${DEBUG}" -a "${loaded}" != "0" ] && \
				echo "not loaded"

			[ -z "${DEBUG}" -a "${loaded}" = "0" ] && \
				[ -z "${QUIET}" ] && \
				printf "%b" "${x} "
		else
			[ -z "${QUIET}" ] && \
				printf "%b\n" "${BOLD}   ::${NORMAL} Skipping ${x} ..."
		fi
	done
	[ -n "${MODS}" ] && [ -z "${QUIET}" ] && echo
}

uppercase() {
	# needs tr on busybox
	echo $1 | tr 'a-z' 'A-Z'
}


findmediamount() {
	# $1 = mount dir name / media name
	# $2 = recognition file
	# $3 = variable to have the device path
	# $4 = actual mount dir path (full path)
	# args remaining are possible devices

	local media=$1 recon=$2 vrbl=$3 mntdir=$4
	shift 4

	good_msg "Looking for the ${media}" ${CRYPT_SILENT}

	if [ "$#" -gt "0" ]
	then
		[ ! -d "${mntdir}" ] && mkdir -p ${mntdir} >/dev/null 2>&1
		if [ -n "${ISOBOOT}" ]
		then
			mntcddir="${mntdir%${media}}iso"
			if [ ! -f "${mntcddir}" ]
			then
				mkdir "${mntcddir}"
			fi
		else
			mntcddir="${mntdir}"
		fi

		for x in $*
		do
			# Check for a block device to mount
			if [ -b "${x}" ]
			then
				skip=0
				bsn=$(basename "${x}")
				#
				# If disk and it has at least one partition, skip.
				# We use /sys/block/${bsn}/${bsn}[0-9]* to make sure that we
				# don't skip device mapper devices. Even the craziest scenario
				# deserves a fair chance.
				#
				for part in $(ls /sys/block/${bsn}/${bsn}*[0-9]* 2>/dev/null)
				do
					skip=1
					break;
				done
				if [ ${skip} -eq 1 ]
				then
					continue
				fi
				good_msg "Attempting to mount media: ${x}" ${CRYPT_SILENT}

				mount -t ${CDROOT_TYPE} ${x} ${mntcddir} >/dev/null 2>&1
				if [ $? -eq 0 ]
				then
					if [ -n "${ISOBOOT}" ]
					then
						if [ -f "${mntcddir}/${ISOBOOT}" ]
						then
							mount -o loop "${mntcddir}/${ISOBOOT}" "${mntdir}"
							if [ $? -eq 0 ]
							then
								good_msg "iso mounted on ${mntdir}"
							fi
						fi
					fi

					# Check for the media
					if [ -f "${mntdir}/${recon}" ]
					then
						#set REAL_ROOT, CRYPT_ROOT_KEYDEV or whatever ${vrbl} is
						eval ${vrbl}'='"${x}"
						good_msg "Media found on ${x}" ${CRYPT_SILENT}
						break
					else
						umount ${mntcddir}
					fi
				fi
			fi
		done
	fi

	eval local result='$'${vrbl}

	[ -n "${result}" ] || bad_msg "Media not found" ${CRYPT_SILENT}
}

devicelist() {
	# Locate the cdrom device with our media on it.
	# CDROM DEVICES
	local DEVICES="/dev/cdroms/* /dev/ide/cd/* /dev/sr*"
	# USB Keychain/Storage
	DEVICES="${DEVICES} /dev/sd*"
	# IDE devices
	DEVICES="${DEVICES} /dev/hd*"
	# virtio devices
	DEVICES="${DEVICES} /dev/vd*"
	# USB using the USB Block Driver
	DEVICES="${DEVICES} /dev/ubd* /dev/ubd/*"
	# iSeries devices
	DEVICES="${DEVICES} /dev/iseries/vcd*"
	# builtin mmc/sd card reader devices
	DEVICES="${DEVICES} /dev/mmcblk* /dev/mmcblk*/*"
	# fallback scanning, this might scan something twice, but it's better than
	# failing to boot.
	[ -e /proc/partitions ] && DEVICES="${DEVICES} $(awk '/([0-9]+[[:space:]]+)/{print "/dev/" $4}' /proc/partitions)"
	echo ${DEVICES}
}

bootstrapFS() {
	if [ "${aufs}" = '1' ]
	then
		# Directories used for rw aufs mount filesystem
		aufs_union=/union aufs_memory=/memory

		# Mountpoint for the aufs dev
		aufs_dev_mnt=/mnt/aufs-dev

		if [ -z "${aufs_dev_uid}" ]
		then
			aufs_branch=${aufs_memory}/aufs-rw-branch/default
		else
			aufs_branch=${aufs_memory}/aufs-rw-branch/${aufs_dev_uid}
		fi

		mkdir -p ${aufs_memory} ${aufs_union} ${aufs_dev_mnt}
	else
		# Legacy SquashFS implementation
		good_msg "Making tmpfs for ${NEW_ROOT}"
		mount -n -t tmpfs tmpfs ${NEW_ROOT}
	fi

	# Setup the filesystem nodes and directories
	for i in ${CDROOT_PATH} /mnt/livecd /mnt/key /mnt/gentoo /tmp /tmp/.initrd /dev /proc /run /sys; do
		mkdir -p "${NEW_ROOT}${i}"
		chmod 755 "${NEW_ROOT}${i}"
	done

	[ ! -d "${CDROOT_PATH}" ] && mkdir -p "${CDROOT_PATH}"
	[ ! -e "${NEW_ROOT}/dev/null" ] && mknod -m 666 "${NEW_ROOT}"/dev/null c 1 3
	[ ! -e "${NEW_ROOT}/dev/zero" ] && mknod -m 666 "${NEW_ROOT}"/dev/zero c 1 5
	[ ! -e "${NEW_ROOT}/dev/console" ] && mknod -m 600 "${NEW_ROOT}"/dev/console c 5 1
	[ ! -e "${NEW_ROOT}/dev/ttyS0" ] && mknod -m 660 "${NEW_ROOT}"/dev/ttyS0 c 4 64

	# For SGI LiveCDs
	if [ "${LOOPTYPE}" = "sgimips" ]
	then
		[ ! -e "${NEW_ROOT}/dev/sr0" ] && mknod "${NEW_ROOT}/dev/sr0" b 11 0
		[ ! -e "${NEW_ROOT}/dev/loop0" ] && mknod "${NEW_ROOT}/dev/loop0" b 7 0
	fi

	# Required for splash to work. Not an issue with the initrd as this
	# device isn't created there and is not needed.
	for minor in 0 1
	do
		[ ! -e "${NEW_ROOT}/dev/${minor}" ] && mknod -m 600 "${NEW_ROOT}/dev/tty${minor}" c 4 ${minor}
	done
}

bootstrapCD() {
	local DEVICES=

	# The device was specified on the command line, so there's no need
	# to scan a bunch of extra devices
	[ -n "${CDROOT_DEV}" ] && DEVICES="${CDROOT_DEV}"
	[ -z "${CDROOT_DEV}" ] && DEVICES=$(devicelist)

	findmediamount "cdrom" "${SUBDIR}/${CDROOT_MARKER}" \
		"REAL_ROOT" "${CDROOT_PATH}" ${DEVICES}

	if [ "${VERIFY}" = '1' ]
	then
		cd "${CDROOT_PATH}"
		if [ -f isoroot_checksums ]
		then
			good_msg "Verifying checksums, this may take some time ..."
			if ! busybox sha512sum -c isoroot_checksums
			then
				bad_msg "Some checksums failed, press any key to poweroff ..."
				read -n1 -s
				busybox poweroff -f
			else
				good_msg "Checksums all valid, continuing boot ..."
			fi
			cd "${OLDPWD}"
		else
			bad_msg "Verify enabled but no checksums file exists, skipping"
		fi
	fi
}

bootstrapKey() {
	# $1 = ROOT/SWAP
	local KEYDEVS=$(devicelist)
	eval local keyloc='"${CRYPT_'${1}'_KEY}"'

	findmediamount "key" "${keyloc}" "CRYPT_${1}_KEYDEV" "/mnt/key" ${KEYDEVS}
}

cache_cd_contents() {
	# Check loop file exists and cache to ramdisk if DO_cache is enabled
	if [ "${LOOPTYPE}" != "noloop" ] && [ "${LOOPTYPE}" != "sgimips" ]
	then
		check_loop
		if [ "${DO_cache}" ]
		then
			# TODO: Check the size of the image versus the size of our tmpfs
			# along with the amount of available RAM and increase tmpfs size
			# if necessary. (Not having awk sucks...)
			# z=0
			# for i in $(cat /proc/meminfo | grep -e ^MemFree -e ^Cached | \
			# cut -d: -f2 | cut -dk -f1 | sed -e "s/^\s*//") ; do
			# z=$((${z} + ${i})) ; done
			# echo ${z}
			good_msg "Copying loop file for caching ..."
			# Verify that the needed directory exists
			mkdir -p "$(dirname ${NEW_ROOT}/mnt/${LOOP})"
			cp -a ${CDROOT_PATH}/${LOOP} ${NEW_ROOT}/mnt/${LOOP}
			if [ $? -ne 0 ]
			then
				warn_msg "Failed to cache the loop file! Lack of RAM?"
				rm -rf ${NEW_ROOT}/mnt/${LOOP} 2>/dev/null
				rm -rf ${NEW_ROOT}/mnt/livecd.* 2>/dev/null
				rm -rf ${NEW_ROOT}/mnt/image.* 2>/dev/null
				rm -rf ${NEW_ROOT}/mnt/zisofs 2>/dev/null
			fi
		fi
	fi
}

mount_sysfs() {
	mount -t sysfs sysfs /sys -o noexec,nosuid,nodev >/dev/null 2>&1
	[ $? -eq 0 ] || bad_msg "Failed to mount /sys!"
}

# Check support for both aufs and overlayfs
# union file system style support
#
is_union_modules() {
	local mod mod_dir

	case $1 in
		aufs)
			mod=${aufs_modules}
			mod_dir=${aufs_modules_dir}
			;;
		overlayfs)
			mod=${overlayfs_modules}
			mod_dir=${overlayfs_modules_dir}
	esac

	# When {aufs,overlayfs}.modules= is used or $CDROOT_PATH/modules
	# directory is available
	if [ "${mod}" = '1' -o -d ${CDROOT_PATH}/modules ]
	then
		if [ -d ${CDROOT_PATH}/modules ]
		then
			warn_msg "Adding all modules in ${CDROOT_PATH}/modules"
			union_insert_modules "${CDROOT_PATH}"/modules
		# Is it a block device?
		elif [ ! -b "${mod_dir}" ]
		then
			bad_msg "${mod_dir} is not a valid block device"
			bad_msg "aborting modules insert into ${CHROOT}"
		else
			warn_msg "Adding all modules in ${mod_dir}"

			mkdir /mnt/modules
			mount "${mod_dir}" /mnt/modules
			union_insert_modules /mnt/modules
		fi
	fi

	return 0
}

# Insert a directory tree $2 to a aufs union specified by $1
# Top-level read-write branch is specified by it's index 0
# $1 = union absolute path (starting with /)
# $2 = path to data directory
#
aufs_insert_dir() {
	# Always mount it over the precedent (add:1:)
	if mount -n -o "remount,add:1:$2=rr" aufs "$1"
	then
		good_msg "Addition of $2 to $1 successful"
	fi
}

# Insert all modules found in $1, usually $CDROOT_PATH
# added to allow users to add their own apps.
union_insert_modules() {
	local module

	for module in "$1/"*.lzm; do
		if [ "${overlayfs}" = '1' ]
		then
			if union_mod overlayfs "${module}"
			then
				good_msg "Addition of '${module}' to overlay successful"
			else
				bad_msg "Unable to insert module: '${module}'"
			fi

			# Used in setup_overlayfs()
			mod_path="${mod_path}:${mod_dir}/.${mod}"

			# Assign variable with paths to modules mount point
			# TODO: Stop using eval
			eval ${mod}="${mod_dir}/.${mod}"
			mods="${mods} ${mod}"
		else
			union_mod aufs "${module}" || bad_msg "Unable to insert module: '${module}'"
		fi
	done
}

# Helper function for union_insert_modules()
union_mod() {
	[ -e "$2" ] || return 0

	mod_dir=/mnt/overlay

	mod=${2##*/}
	mod=${mod//-/_}
	mod=${mod%.*}

	if [ "${aufs}" = '1' ]
	then
		if [ ! -d "${aufs_union}"/mnt/"${mod}" ]
		then
			mkdir -p "${aufs_union}"/mnt/modules/"${mod}" || return
		fi

		mount -o loop,ro "$2" "${aufs_union}"/mnt/modules/"${mod}"
		aufs_insert_dir "${aufs_union}" "${aufs_union}"/mnt/modules/"${mod}"
	else
		if [ ! -d "${mod_dir}/.${mod}" ]
		then
			mkdir -p "${mod_dir}/.${mod}" || return
		fi

		mount -o loop,ro "$2" "${mod_dir}/.${mod}"
	fi
}

# Implements no_umounts variable into $CHROOT/etc/conf.d/localmount for a cleaner shutdown process
conf_rc_no_umounts() {
	local conf nomount fnd
	conf=${CHROOT}/etc/conf.d/localmount fnd=0

	if nomount=$(grep -n '^[[:blank:]]*no_umounts=' ${conf})
	then
		local i n data cmd IFS
		IFS='
'
		set -- ${nomount}
		unset IFS

		for i
		do
			n=${i%%:*}; i=${i#"$n"}
			data=${i#*=}

			case ${data} in
				"\"${no_umounts}\""|"'${no_umounts}'") fnd=1;;
				*) cmd="${cmd}${n} d;"
			esac
		done

		if [ -n "${cmd}" ]
		then
			sed -i "${cmd%;}" ${conf}
			test_success "Unable to edit /etc/conf.d/localmount"
		fi
	fi

	if [ ${fnd} -eq 0 ]
	then
		printf 'no_umounts="%s"\n' "${no_umounts}" >> ${conf}
		test_success "Unable to write to /etc/conf.d/localmount"
	fi
}

# is_int "${A}" ["${B}"..]
# NOTE we consider a leading 0 false as it would be interpreted as octal
is_int() {
	local i
	for i
	do
		case ${i} in
			''|*[!0-9]*|0?*) return 1 ;;
			*) :
		esac
	done
}

# Function to create an ext2 fs on $aufs_dev, $aufs_dev_mnt mountpoint
create_changefs() {
	local size

	while :;
	do
		read -p '<< Size of file (Press Enter for default 256 MB): ' size

		size=${size:-256}

		if ! is_int ${size}
		then
			bad_msg "Non numeric value given for size, try again"
			continue
		elif [ 15 -ge "${size}" ]
		then
			bad_msg "Please give a size of at least 16 Megabytes"
		else
			if dd if=/dev/zero "of=${aufs_dev_mnt}${aufs_union_file}" bs=1 seek="${size}"M count=0 >/dev/null 2>&1
			then
				good_msg "Creation of ${aufs_union_file}, ${size}MB on ${aufs_dev successful}, formatting it ext2"
				mke2fs -F "${aufs_dev_mnt}${aufs_union_file}" >/dev/null 2>&1
				break
			else
				rm "${aufs_dev_mnt}${aufs_union_file}"
				bad_msg "Unable to create ${aufs_union_file#*/} on ${aufs_dev} of ${size}MB"
				bad_msg "Ensure your disk is not full or read-only"

				read -p '<< Type "a" to abort, anything else to continue : ' doabort
				if [ "${doabort}" = 'a' ]
				then
					bad_msg "Aborting creation of ${aufs_union_file}!"
					umount "${aufs_dev}" && rmdir "${aufs_dev_mnt}"
					return 1
				fi
			fi
		fi
	done
	return $?
}

setup_aufs() {
	bootstrapCD

	if [ "${aufs_dev}" = "search" ]
	then
		findmediamount "aufs-dev" "${aufs_union_file}" \
			"aufs_dev" "${aufs_dev_mnt}" $(devicelist)
		aufs_mounted="1"
	elif [ -z "${aufs_dev}" ] && [ -w "${CDROOT_PATH}/${aufs_union_file}" ]
	then
		aufs_dev="${REAL_ROOT}"
		aufs_dev_mnt="${CDROOT_PATH}"
		aufs_mounted="1"
	fi

	if [ -z "${aufs_dev}" ] && [ -w "${CDROOT_PATH}/casper-rw" ]
	then
		aufs_dev="${REAL_ROOT}"
		aufs_dev_mnt="${CDROOT_PATH}"
		aufs_union_file="/casper-rw"
		aufs_mounted="1"
	fi

	if [ -n "${aufs_dev}" ]
	then
		if [ ! -b "${aufs_dev}" ]
		then
			bad_msg "${aufs_dev} is not a valid block device"
			local invalidblk=1
			unset aufs_dev
		#skip this block when aufs_dev_mnt is already mounted
		elif [ "${aufs_mounted}" != "1" ]
		then
			good_msg "Mounting ${aufs_dev} to ${aufs_memory} for aufs support"

			if ! mount -t auto "${aufs_dev}" "${aufs_dev_mnt}" >/dev/null 2>&1
			then
				bad_msg "Mount of ${aufs_dev} failed, falling back to ramdisk based aufs"
				unset aufs_dev
			fi
		fi

		# Check and attempt to create the AUFS union file
		if [ ! -e ${aufs_dev_mnt}${aufs_union_file} ] && [ -n "${aufs_dev}" ]
		then
			create_changefs && mount -t auto "${aufs_dev_mnt}${aufs_union_file}" "${aufs_memory}"
		elif [ -n "${aufs_dev}" ]
		then
			while :;
			do
				if mount -t auto "${aufs_dev_mnt}${aufs_union_file}" "${aufs_memory}" >/dev/null 2>&1
				then
					if [ "${aufs_union_file}" = "/casper-rw" ]
					then
						bad_msg "Use of livecd.aufs preferred to casper-rw for changes saving, please rename the file."
					fi
					break
				else
					bad_msg "Mounting of changes file failed, Running e2fsck"

					if ! hash e2fsck >/dev/null 2>&1
					then
						bad_msg "/sbin/e2fsck not found! aborting filesystem check"
						bad_msg "Moving ${aufs_union_file#*/} to ${aufs_union_file#*/}.bad"

						mv "${aufs_dev_mnt}${aufs_union_file}" "${aufs_dev_mnt}${aufs_union_file}.bad"
						break
					fi

					if e2fsck "${aufs_dev_mnt}${aufs_union_file}" >/dev/null 2>&1
					then
						good_msg "e2fsck ran successfully. Please verify data after bootup"
					else
						bad_msg "Your ${aufs_union_file#*/} image might be corrupted"
						bad_msg "moving ${aufs_union_file#*/} to ${aufs_union_file#*/}.bad"

						mv "${aufs_dev_mnt}${aufs_union_file}" "${aufs_dev_mnt}${aufs_union_file}.bad"
						break
					fi
				fi
			done
		fi

		# Mount tmpfs only in the case when aufs= boot parameter was
		# empty or we were not able to mount the storage device
		if [ "${CDROOT}" = '1' ] && [ ! -f "${aufs_dev_mnt}${aufs_union_file}" ]
		then
			aufs_xino=${aufs_memory}
			umount "${aufs_memory}" >/dev/null 2>&1

			if [ "${invalidblk}" = '1' ]
			then
				bad_msg "Verify that you've entered a valid device path"
			else
				bad_msg "Create an extfs ${aufs_union_file#*/} file on this device"
			fi

			bad_msg "if you wish to have aufs data persistency on reboots"
			bad_msg "Falling back to ramdisk based aufs"
			good_msg "Mounting ramdisk to ${aufs_memory} for aufs support"

			mount -t tmpfs tmpfs "${aufs_memory}"
		else
			aufs_xino=${aufs_memory}/xino

			mkdir -p "${aufs_xino}"
			mount -t tmpfs aufs-xino "${aufs_xino}"
		fi
	else
		aufs_xino=${aufs_memory}

		good_msg "Mounting ramdisk to ${aufs_memory} for aufs support"
		mount -t tmpfs tmpfs "${aufs_memory}"
	fi

	mkdir -p "${aufs_branch}"
	if ! mount -t aufs -n -o "nowarn_perm,udba=none,xino=${aufs_xino}/.aufs.xino,br:${aufs_branch}=rw" aufs "${aufs_union}"
	then
		bad_msg "Can't setup union ${aufs_union} in directory!"
		aufs=0
	fi
}

setup_overlayfs() {
	# Setup directories and vars
	local overlay=/mnt/overlay
	local upperdir="${overlay}/.upper"
	local workdir="${overlay}/.work"
	local static=/mnt/livecd

	rundebugshell overlayfs
	for i in "${overlay}" "${static}"
	do
		[ ! -d "${i}" ] && mkdir -p "${i}"
	done

	good_msg "Loading overlayfs"
	modprobe overlay >/dev/null 2>&1
	checkfs overlay

	mount -t squashfs -o loop,ro "${CDROOT_PATH}/${LOOPEXT}${LOOP}" "${static}"
	mount -t tmpfs none "${overlay}"
	mkdir "${upperdir}" "${workdir}"

	is_union_modules overlayfs
	mount -t overlay overlay -o lowerdir="${static}${mod_path}",upperdir="${upperdir}",workdir="${workdir}" "${NEW_ROOT}"

	[ ! -d "${NEW_ROOT}${overlay}" ] && mkdir -p "${NEW_ROOT}${overlay}"
	[ ! -d "${NEW_ROOT}${static}" ] && mkdir -p "${NEW_ROOT}${static}"

	echo "overlay / overlay defaults 0 0" > "${NEW_ROOT}"/etc/fstab

	for i in "${overlay}" "${static}"
	do
		mount --bind "${i}" "${NEW_ROOT}${i}"
	done

	# Did we populate the overlayfs modules path locations variable?
	if [ -n "${mods}" ]
	then
		for i in ${mods}
		do
			mount --bind "${overlay}/.${i}" "${NEW_ROOT}/${overlay}/.${i}"
		done
	fi
}


findnfsmount() {
	if start_network
	then
		[ -e /rootpath ] && NFSROOT=$(cat /rootpath)

		if [ -z "${NFSROOT}" ]
		then
			# Obtain NFSIP
			OPTIONS=$(busybox dmesg | grep rootserver | sed -e "s/,/ /g")
			for OPTION in ${OPTIONS}
			do
				if [ $(echo ${OPTION} | sed -e "s/=/ /g" | cut -d " " -f 1) = 'rootserver' ]
				then
					NFSIP=$(echo ${OPTION} | sed -e "s/=/ /g" | cut -d " " -f 2)
				fi
			done

			# Obtain NFSPATH
			OPTIONS=$(busybox dmesg | grep rootpath | sed -e "s/,/ /g")
			for OPTION in ${OPTIONS}
			do
				if [ $(echo ${OPTION} | sed -e "s/=/ /g" | cut -d " " -f 1) = 'rootpath' ]
				then
					NFSPATH=$(echo ${OPTION} | sed -e "s/=/ /g" | cut -d " " -f 2)
				fi
			done

			# Setup NFSROOT
			if [ -n "${NFSIP}" -a -n "${NFSPATH}" ]
			then
				NFSROOT="${NFSIP}:${NFSPATH}"
			else
				bad_msg "The DHCP Server did not send a valid root-path."
				bad_msg "Please check your DHCP setup, or provide a nfsroot=<...> parameter."
				return 1
			fi
		fi

		if [ -n "${NFSROOT}" ]
		then
			NFSOPTIONS=${NFSROOT#*,}
			NFSROOT=${NFSROOT%%,*}
			if [ "${NFSOPTIONS}" = "${NFSROOT}" ]
			then
				NFSOPTIONS=${DEFAULT_NFSOPTIONS}
			else
				NFSOPTIONS="${DEFAULT_NFSOPTIONS},${NFSOPTIONS}"
			fi

			if [ "${CDROOT}" != '0' ]
			then
				good_msg "Attempting to mount NFS CD image on ${NFSROOT} with options ${NFSOPTIONS}"
				mount -t nfs -o ${NFSOPTIONS} ${NFSROOT} ${CDROOT_PATH}
				if [ $? -eq 0 ]
				then
					REAL_ROOT="/dev/nfs"
				else
					bad_msg "NFS Mounting failed. Is the path corrent ?"
					return 1
				fi
			else
				good_msg "Attempting to mount NFS root on ${NFSROOT} with options ${NFSOPTIONS}"
				mount -t nfs -o ${NFSOPTIONS} ${NFSROOT} ${NEW_ROOT}
				if [ $? -eq 0 ]
				then
					REAL_ROOT="/dev/nfs"
				else
					bad_msg "NFS Mounting failed. Is the path correct ?"
					return 1
				fi
				# FIXME: Need to start portmap and the other rpc daemons in
				# order to remount rw.
			fi

		fi
	else # IP / DHCP
		return 1
	fi
}

find_real_device() {
	local DEVICE="${1}"
	case "${DEVICE}" in
		UUID\=*|LABEL\=*|PARTUUID\=*)
			local REAL_DEVICE=""
			local retval=1

			if [ ${retval} -ne 0 ]
			then
				REAL_DEVICE=$(findfs "${DEVICE}" 2>/dev/null)
				retval=$?
			fi

			if [ ${retval} -ne 0 ]
			then
				REAL_DEVICE=$(blkid -o device -l -t "${DEVICE}" 2>/dev/null)
				retval=$?
			fi

			if [ ${retval} -eq 0 ] && [ -n "${REAL_DEVICE}" ]
			then
				DEVICE="${REAL_DEVICE}"
			fi
		;;
	esac
	printf "%s" "${DEVICE}"
}

check_loop() {
	if [ -z "${LOOP}" -o ! -e "${CDROOT_PATH}/${LOOP}" ]
	then

		bad_msg "Invalid loop location: ${LOOP}"
		bad_msg 'Please export LOOP with a valid location, or reboot and pass a proper loop=...'
		bad_msg 'kernel command line!'

		run_shell
	fi
}

run_shell() {
	[ -x /bin/sh ] && SH=/bin/sh || SH=/bin/ash

	export PS1='rescueshell \w \# '

	if [ -n "${CONSOLE}" ] && [ -c "/dev/${CONSOLE}" ]
	then
		setsid ${SH} -c "exec sh --login </dev/${CONSOLE} >/dev/${CONSOLE} 2>&1"
	elif command -v cttyhack 1>/dev/null 2>&1
	then
		setsid cttyhack ${SH} --login
	elif [ -c '/dev/tty1' ]
	then
		setsid ${SH} -c 'exec sh --login </dev/tty1 >/dev/tty1 2>&1'
	else
		${SH} --login
	fi

	echo

	:> "${GK_SHELL_LOCKFILE}"
}

fs_type_in_use() {
	fs_type=$1
	cut -d ' ' -f 3 < /proc/mounts | fgrep -q "${fs_type}"
}

mount_devfs() {
	# Use devtmpfs if enabled in kernel,
	# else tmpfs. Always run mdev just in case
	local devfs=tmpfs

	if checkfs devtmpfs >/dev/null
	then
		devfs=devtmpfs
	fi

	# Options copied from /etc/init.d/udev-mount, should probably be kept in sync
	if ! fs_type_in_use devtmpfs
	then
		mount -t ${devfs} -o "exec,nosuid,mode=0755,size=10M" udev /dev \
			|| bad_msg "Failed to mount /dev as ${devfs}"
	fi

	# http://git.busybox.net/busybox/plain/docs/mdev.txt
	if ! fs_type_in_use devpts
	then
		mkdir -m 0755 /dev/pts
		mount -t devpts -o gid=5,mode=0620 devpts /dev/pts || bad_msg "Failed to mount /dev/pts"
	fi
}

test_success() {
	retcode=$?
	# If last command failed send error message and fall back to a shell
	if [ "${retcode}" != '0' ]
	then
		error_string=${1}
		error_string="${error_string:-run command}"
		bad_msg 'Failed to ${1}; failing back to the shell ...'
		run_shell
	fi
}


# msg functions arguments
# $1 string
# $2 hide flag

good_msg() {
	[ -n "${QUIET}" ] && [ -z "${DEBUG}" ] && return 0

	msg_string=${1}
	msg_string="${msg_string:-...}"
	[ "$2" != '1' ] && printf "%b\n" "${GOOD}>>${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
}

good_msg_n() {
	[ -n "${QUIET}" ] && [ -z "${DEBUG}" ] && return 0

	msg_string=${1}
	msg_string="${msg_string:-...}"
	[ "$2" != '1' ] && printf "%b" "${GOOD}>>${NORMAL}${BOLD} ${msg_string}"
}

bad_msg() {
	msg_string=${1}
	msg_string="${msg_string:-...}"
	if [ "$2" != '1' ]
	then
		splash 'verbose' >/dev/null &
		printf "%b\n" "${BAD}!!${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
	fi
}

warn_msg() {
	msg_string=${1}
	msg_string="${msg_string:-...}"
	[ "$2" != '1' ] && printf "%b\n" "${WARN}**${NORMAL}${BOLD} ${msg_string} ${NORMAL}"
}

crypt_filter() {
	if [ "${CRYPT_SILENT}" = '1' ]
	then
		eval $1 >/dev/null 2>&1
	else
		splash 'verbose' >/dev/null &
		eval $1
		res=$?
		if [ ${res} -eq 0 ]
		then
			splash set_msg 'Disk unlocked.'
		fi
		return ${res}
	fi
}

prompt_user() {
	# $1 = variable whose value is the path (examples: "REAL_ROOT",
	#      "LUKS_KEYDEV")
	# $2 = label
	# $3 = optional explanations for failure

	eval local oldvalue='$'${1}

	if [ $# != 2 -a $# != 3 ]
	then
		bad_msg "Bad invocation of function prompt_user."
		bad_msg "Please file a bug report with this message"
		exit 1
	fi
	[ -n "${3}" ] && local explnt=" or : ${3}" || local explnt="."

	bad_msg "Could not find the ${2} in ${oldvalue}${explnt}"
	bad_msg "Please specify another value or:"
	bad_msg "- press Enter for the same"
	bad_msg '- type "shell" for a shell'
	bad_msg '- type "q" to skip ...'
	printf "%s" "${2}(${oldvalue}) :: "
	read ${1}
	#if [ $? -gt 0 ]
	#then
	#	# prompt timed out
	#	printf "\n"
	#fi

	case $(eval echo '$'${1}) in
		'q')
			eval ${1}'='${oldvalue}
			warn_msg "Skipping step, this will likely cause a boot failure."
			;;
		'shell')
			eval ${1}'='${oldvalue}
			warn_msg "To leave and try again just press <Ctrl>+D"
			run_shell
			;;
		'')
			eval ${1}'='${oldvalue}
			;;
	esac
}

cmdline_hwopts() {
	# Scan CMDLINE for any "doscsi" or "noscsi"-type arguments
	local FOUND
	local TMP_HWOPTS

	for x in ${HWOPTS}
	do
		for y in ${CMDLINE}
		do
			if [ "${y}" = "do${x}" ]
			then
				MY_HWOPTS="${MY_HWOPTS} ${x}"
			elif [ "${y}" = "no${x}" ]
			then
				MY_HWOPTS="$(echo ${MY_HWOPTS} | sed -e "s/${x}//g" -)"
			fi
			if [ "$(echo ${y} | cut -b -7)" = "keymap=" ]
			then
				MY_HWOPTS="${MY_HWOPTS} keymap"
			fi
		done
	done

	# Shouldnt need to sort this as the following loop should figure out the
	# duplicates and strip them out
	#MY_HWOPTS=$(echo ${MY_HWOPTS} | sort)

	for x in ${MY_HWOPTS}
	do
		FOUND=0
		for y in ${TMP_HWOPTS}
		do
			if [ "${y}" = "${x}" ]
			then
				continue 2
			fi
		done
		TMP_HWOPTS="${TMP_HWOPTS} ${x}"
		eval DO_$(echo ${x} | sed 's/-//')=1
	done

	MY_HWOPTS=${TMP_HWOPTS}
}

load_modules() {
	# Load modules listed in MY_HWOPTS if /lib/modules exists for the running
	# kernel version
	if [ -d "/lib/modules/${KV}" ]
	then
		good_msg 'Loading modules'
		# Load appropriate kernel modules
		for modules in ${MY_HWOPTS}
		do
			modules_scan ${modules}
		done
	else
		good_msg 'Skipping module load; no modules in the ramdisk!'
	fi
}

setup_keymap() {
	if [ "${DO_keymap}" ]
	then
		if [ ! -e /dev/vc/0 -a ! -e /dev/tty0 ]
		then
			DEVBIND=1
			mount -o bind ${NEW_ROOT}/dev /dev
		fi
		[ ! -e /dev/tty0 ] && ln -s /dev/tty1 /dev/tty0

		[ -f /lib/keymaps/keymapList ] && chooseKeymap

		[ "${DEVBIND}" = '1' ] && umount /dev
	fi
}

setup_locale() {
	if [ -n "${locale}" ]
	then
		echo "LANG=${locale}" >${NEW_ROOT}/etc/sysconfig/locale
	fi
}

chooseKeymap() {
	good_msg "Loading keymaps"
	if [ -z "${keymap}" ]
	then
		splash 'verbose' >/dev/null &
		cat /lib/keymaps/keymapList
		read -t 10 -p '<< Load keymap (Enter for default): ' keymap
		case ${keymap} in
			1|azerty) keymap=azerty ;;
			2|be) keymap=be ;;
			3|bg) keymap=bg ;;
			4|br-a) keymap=br-a ;;
			5|br-l) keymap=br-l ;;
			6|by) keymap=by ;;
			7|cf) keymap=cf ;;
			8|croat) keymap=croat ;;
			9|cz) keymap=cz ;;
			10|de) keymap=de ;;
			11|dk) keymap=dk ;;
			12|dvorak) keymap=dvorak ;;
			13|es) keymap=es ;;
			14|et) keymap=et ;;
			15|fi) keymap=fi ;;
			16|fr) keymap=fr ;;
			17|gr) keymap=gr ;;
			18|hu) keymap=hu ;;
			19|il) keymap=il ;;
			20|is) keymap=is ;;
			21|it) keymap=it ;;
			22|jp) keymap=jp ;;
			23|la) keymap=la ;;
			24|lt) keymap=lt ;;
			25|mk) keymap=mk ;;
			26|nl) keymap=nl ;;
			27|no) keymap=no ;;
			28|pl) keymap=pl ;;
			29|pt) keymap=pt ;;
			30|ro) keymap=ro ;;
			31|ru) keymap=ru ;;
			32|se) keymap=se ;;
			33|sg) keymap=sg ;;
			34|sk-y) keymap=sk-y ;;
			35|sk-z) keymap=sk-z ;;
			36|slovene) keymap=slovene ;;
			37|trf) keymap=trf ;;
			38|trq) keymap=trq ;;
			39|ua) keymap=ua ;;
			40|uk) keymap=uk ;;
			41|us) keymap=us ;;
			42|wangbe) keymap=wangbe ;;
			43|sf|ch*) keymap=sf ;;
		esac
	fi
	if [ -e /lib/keymaps/${keymap}.map ]
	then
		good_msg "Loading the '${keymap}' keymap ..."
		loadkmap < /lib/keymaps/${keymap}.map
#		xkeymap=${keymap}
#		echo ${keymap} | egrep -e "[0-9]+" >/dev/null 2>&1
#		if [ $? -eq 0 ]
#		then
#			xkeymap=$(tail -n 8 /lib/keymaps/keymapList | grep ${keymap} | sed -r "s/.*\s+${keymap}\s+([a-z-]+).*/\1/g" | egrep -v 1)
#		fi
		mkdir -p /etc/sysconfig
#		echo "XKEYBOARD=${xkeymap}" > /etc/sysconfig/keyboard
		echo "XKEYBOARD=${keymap}" > /etc/sysconfig/keyboard
		splash set_msg "Set keymap to '${keymap}'"
	elif [ -z "${keymap}" ]
	then
		good_msg
		good_msg "Keeping default keymap"
		splash set_msg "Keeping default keymap"
	else
		bad_msg "Sorry, but keymap '${keymap}' is invalid!"
		unset keymap
		chooseKeymap
	fi
}

#
# Copy over user selected keymap
#
copyKeymap() {
	if [ -e /etc/sysconfig/keyboard -a ${CDROOT} -eq 1 ]
	then
		[ ! -d ${NEW_ROOT}/etc/sysconfig ] && mkdir -p ${NEW_ROOT}/etc/sysconfig
		cp /etc/sysconfig/keyboard ${NEW_ROOT}/etc/sysconfig/keyboard
	fi
}

# This helper function is to be called using call_func_timeout.
# It enables us to wait a reasonable amount of time until /dev/zfs appears.
waitForZFS() {
	while [ ! -c /dev/zfs ]
	do
		echo >/dev/null
	done

	exit 1
}

start_volumes() {
	# Here, we check for /dev/device-mapper, and if it exists, we setup a
	# a symlink, which should hopefully fix bug #142775 and bug #147015
	if [ -e /dev/device-mapper ] && [ ! -e /dev/mapper/control ]
	then
		mkdir -p /dev/mapper
		ln -sf /dev/device-mapper /dev/mapper/control
	fi

	if [ "${USE_MDADM}" = '1' ]
	then
		if [ -x '/sbin/mdadm' ]
		then
			/sbin/mdadm --assemble --scan
			#Intel Matrix RAID (and possibly others) have a container layer above the actual volumes,
			#So we have to look for volumes that haven't been activated.
			mdadm -IRs
		else
			bad_msg "mdadm not found: skipping mdadm raid assembly!"
		fi
	fi

	if [ "${USE_MULTIPATH_NORMAL}" = '1' ]
	then
		for multipath_path in /sbin/multipath /bin/multipath MISSING
		do
			[ -x "${multipath_path}" ] && break
		done

		for dmsetup_path in /sbin/dmsetup /bin/dmsetup MISSING
		do
			[ -x "${dmsetup_path}" ] && break
		done

		for kpartx_path in /sbin/kpartx /bin/kpartx MISSING
		do
			[ -x "${kpartx_path}" ] && break
		done

		fail=0
		[ "${multipath_path}" = "MISSING" ] && fail=1 && bad_msg "domultipath called, but multipath binary missing! Skipping multipath"
		[ "${dmsetup_path}" = "MISSING" ] && fail=1 && bad_msg "domultipath called, but dmsetup binary missing! Skipping multipath"
		[ "${kpartx_path}" = "MISSING" ] && fail=1 && bad_msg "domultipath called, but kpartx binary missing! Skipping multipath"

		if [ ${fail} -eq 0 ]
		then
			good_msg "Scanning for multipath devices"
			good_msg ":: Populating scsi_id info for libudev queries"
			mkdir -p /run/udev/data

			local ech
			for ech in /sys/block/*
			do
				local tgtfile=b$(cat ${ech}/dev)
				/lib/udev/scsi_id -g -x /dev/${ech##*/} |sed -e 's/^/E:/' >/run/udev/data/${tgtfile}
			done

			${multipath_path} -v 0
			sleep 2
			good_msg "Activating multipath devices"
			${dmsetup_path} ls --target multipath --exec "${kpartx_path} -a -v"
		fi
	fi

	if [ "${USE_DMRAID_NORMAL}" = '1' ]
	then
		if [ -x '/sbin/dmraid' ]
		then
			good_msg "Activating Device-Mapper RAID(s)"
			if [ -z "${DMRAID_OPTS}" ]
			then
				/sbin/dmraid -ay
			else
				/sbin/dmraid -ay ${DMRAID_OPTS}
			fi
			[ -x '/sbin/kpartx' ] && /sbin/dmsetup ls --exec '/sbin/kpartx -a -s'
		fi
	fi

	if [ "${USE_LVM_NORMAL}" = '1' ]
	then
		for lvm_path in /sbin/lvm /bin/lvm MISSING
		do
			[ -x "${lvm_path}" ] && break
		done

		if [ "${lvm_path}" = "MISSING" ]
		then
			bad_msg "dolvm invoked, but LVM binary not available! skipping LVM volume group activation!"
		else
			for dev in ${RAID_DEVICES}
			do
				setup_md_device "${dev}"
			done

			# This is needed for LVM to accept the following logic
			lvm_commands="#! ${lvm_path}"

			# If there is a cache, update it. Unbreak at least dmcrypt
			[ -d /etc/lvm/cache ] && lvm_commands="${lvm_commands} \nvgscan"

			# To activate volumegroups on all devices in the cache
			lvm_commands="${lvm_commands} \nvgchange -ay --sysinit"

			# To create symlinks so users can use real_root=/dev/vg/root
			# This needs to run after vgchange, using vgchange --mknodes is too
			# early.
			lvm_commands="${lvm_commands} \nvgmknodes --ignorelockingfailure"

			# And finally execute it all (/proc/... needed if lvm is compiled without readline)
			good_msg "Scanning for and activating Volume Groups"
			printf "%b\n" "${lvm_commands}" | ${lvm_path} /proc/self/fd/0
		fi
	fi

	if [ "${USE_BCACHE}" = '1' ]
	then
		if [ ! -e /sys/fs/bcache/register_quiet ]
		then
			warn_msg "'/sys/fs/bcache/register_quiet' does not exist. Missing kernel driver? Skipping dobcache ..."
		else
			local i=
			for i in $(awk '$4 !~ /^(name$|$)/ { print $4 }' /proc/partitions)
			do
				if [ -e "/dev/${i}" ]
				then
					# Push all the block devices to register_quiet
					# If its bcache, it will bring it up, if not, it will simply ignore it.
					echo "/dev/${i}" >/sys/fs/bcache/register_quiet 2>/dev/null
				else
					warn_msg "'/dev/${i}' should exist but is missing; Ignoring ..."
				fi
			done
		fi
	fi

	if [ "${USE_BTRFS}" = '1' ]
	then
		if [ -x '/sbin/btrfs' ]
		then
			/sbin/btrfs device scan
		else
			bad_msg "btrfs not found: skipping btrfs device scanning!"
		fi
	fi

	if [ "${USE_ZFS}" = '1' ]
	then
		# Avoid race involving asynchronous module loading
		if call_func_timeout waitForZFS 5
		then
			bad_msg "Cannot import ZFS pool because /dev/zfs is missing"
		elif [ -z "${ZFS_POOL}" ]
		then
			good_msg "Importing ZFS pools"

			/sbin/zpool import -N -a ${ZPOOL_CACHE} ${ZPOOL_FORCE}
			if [ $? -eq 0 ]
			then
				good_msg "Importing ZFS pools succeeded"
			else
				bad_msg "Imported ZFS pools failed"
			fi
		else

			if [ "$(zpool list -H -o name ${ZFS_POOL} 2>&1)" = "${ZFS_POOL}" ]
			then
				good_msg "ZFS pool ${ZFS_POOL} already imported."

				if [ -n "${CRYPT_ROOT}" -o -n "${CRYPT_SWAP}" ]
				then
					good_msg "LUKS detected. Reimporting ${ZFS_POOL}"
					/sbin/zpool export -f "${ZFS_POOL}"
					/sbin/zpool import -N ${ZPOOL_CACHE} ${ZPOOL_FORCE} "${ZFS_POOL}"
				fi
			else
				good_msg "Importing ZFS pool ${ZFS_POOL}"

				/sbin/zpool import -N ${ZPOOL_CACHE} ${ZPOOL_FORCE} "${ZFS_POOL}"
				if [ $? -eq 0 ]
				then
					good_msg "Import of ${ZFS_POOL} succeeded"
				else
					bad_msg "Import of ${ZFS_POOL} failed"
				fi
			fi
		fi
	fi
}

start_iscsi() {
	if [ ! -n "${ISCSI_NOIBFT}" ]
	then
		good_msg "Activating iSCSI via iBFT"
		iscsistart -b
	fi

	if [ -n "${ISCSI_INITIATORNAME}" ] && [ -n "${ISCSI_TARGET}" ] && [ -n "${ISCSI_ADDRESS}" ]
	then
		good_msg "Activating iSCSI via cmdline"

		if [ -n "${ISCSI_TGPT}" ]
		then
			ADDITIONAL="${ADDITIONAL} -g ${ISCSI_TGPT}"
		else
			ADDITIONAL="${ADDITIONAL} -g 1"
		fi

		if [ -n "${ISCSI_PORT}" ]
		then
			ADDITIONAL="${ADDITIONAL} -p ${ISCSI_PORT}"
		fi

		if [ -n "${ISCSI_USERNAME}" ]
		then
			ADDITIONAL="${ADDITIONAL} -u ${ISCSI_USERNAME}"
		fi

		if [ -n "${ISCSI_PASSWORD}" ]
		then
			ADDITIONAL="${ADDITIONAL} -w ${ISCSI_PASSWORD}"
		fi

		if [ -n "${ISCSI_USERNAME_IN}" ]
		then
			ADDITIONAL="${ADDITIONAL} -U ${ISCSI_USERNAME_IN}"
		fi

		if [ -n "${ISCSI_PASSWORD_IN}" ]
		then
			ADDITIONAL="${ADDITIONAL} -W ${ISCSI_PASSWORD_IN}"
		fi

		if [ -n "${ISCSI_DEBUG}" ]
		then
			ADDITIONAL="${ADDITIONAL} -d ${ISCSI_DEBUG}"
		fi

		iscsistart -i "${ISCSI_INITIATORNAME}" -t "${ISCSI_TARGET}" -a "${ISCSI_ADDRESS}" ${ADDITIONAL}
	fi
}


# Open a LUKS device
# It is either the root or a swap, other devices are supported in the scripts provided with sys-fs/cryptsetup
# $1 - root/swap
openLUKS() {
	if [ ! -x /sbin/cryptsetup ]
	then
		bad_msg "cryptsetup program is missing. Was initramfs built without --luks parameter?"
		exit 1
	fi

	case $1 in
		root)
			local TYPE=ROOT
			;;
		swap)
			local TYPE=SWAP
			;;
	esac

	eval local LUKS_DEVICE='"${CRYPT_'${TYPE}'}"' LUKS_NAME="$1" LUKS_KEY='"${CRYPT_'${TYPE}'_KEY}"'
	eval local LUKS_KEYDEV='"${CRYPT_'${TYPE}'_KEYDEV}"' LUKS_TRIM='"${CRYPT_'${TYPE}'_TRIM}"'
	eval local OPENED_LOCKFILE='"${CRYPT_'${TYPE}'_OPENED_LOCKFILE}"'
	local DEV_ERROR=0 KEY_ERROR=0 KEYDEV_ERROR=0
	local mntkey="/mnt/key/" crypt_filter_ret= cryptsetup_options=''

	while true
	do
		local gpg_cmd=""
		if [ -e "${OPENED_LOCKFILE}" ]
		then
			good_msg "The LUKS device ${LUKS_DEVICE} meanwhile was opened by someone else."
			break
		# if crypt_silent=1 and some error occurs, enter shell quietly
		elif [ \( ${CRYPT_SILENT} -eq 1 \) -a \( \( \( ${DEV_ERROR} -eq 1 \) -o \( ${KEY_ERROR} -eq 1 \) \) -o \( ${KEYDEV_ERROR} -eq 1 \) \) ]
		then
			run_shell
		elif [ ${DEV_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_DEVICE" "${LUKS_NAME}"
			DEV_ERROR=0
		elif [ ${KEY_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_KEY" "${LUKS_NAME} key"
			KEY_ERROR=0
		elif [ ${KEYDEV_ERROR} -eq 1 ]
		then
			prompt_user "LUKS_KEYDEV" "${LUKS_NAME} key device"
			KEYDEV_ERROR=0
		else
			LUKS_DEVICE=$(find_real_device "${LUKS_DEVICE}")
			if [ -z "${LUKS_DEVICE}" ]
			then
				bad_msg "Looks like CRYPT_${TYPE} kernel cmdline argument is not set." ${CRYPT_SILENT}
				DEV_ERROR=1
				continue
			fi

			setup_md_device ${LUKS_DEVICE}
			cryptsetup isLuks ${LUKS_DEVICE}
			if [ $? -ne 0 ]
			then
				bad_msg "The LUKS device ${LUKS_DEVICE} does not contain a LUKS header" ${CRYPT_SILENT}
				DEV_ERROR=1
				continue
			else
				if [ "x${LUKS_TRIM}" = "xyes" ]
				then
					good_msg "Enabling TRIM support for ${LUKS_NAME} ..." ${CRYPT_SILENT}
					cryptsetup_options="${cryptsetup_options} --allow-discards"
				fi

				# Handle keys
				if [ -n "${LUKS_KEY}" ]
				then
					local REAL_LUKS_KEYDEV="${LUKS_KEYDEV}"
					if [ ! -e "${mntkey}${LUKS_KEY}" ]
					then
						REAL_LUKS_KEYDEV=$(find_real_device "${LUKS_KEYDEV}")
						if [ -b "${REAL_LUKS_KEYDEV}" ]
						then good_msg "Using key device ${REAL_LUKS_KEYDEV}." ${CRYPT_SILENT}
						else
							good_msg "Please insert removable device ${LUKS_KEYDEV} for ${LUKS_NAME}" ${CRYPT_SILENT}
							# abort after 10 secs
							local count=10
							while [ ${count} -gt 0 ]
							do
								count=$((count-1))
								sleep 1
								REAL_LUKS_KEYDEV=$(find_real_device "${LUKS_KEYDEV}")
								if [ -b "${REAL_LUKS_KEYDEV}" ]
								then
									good_msg "Removable device ${REAL_LUKS_KEYDEV} detected." ${CRYPT_SILENT}
									break
								fi
							done
							if [ ! -b "${REAL_LUKS_KEYDEV}" ]
							then
								eval CRYPT_${TYPE}_KEY=${LUKS_KEY}
								bootstrapKey ${TYPE}
								eval LUKS_KEYDEV='"${CRYPT_'${TYPE}'_KEYDEV}"'
								REAL_LUKS_KEYDEV=$(find_real_device "${LUKS_KEYDEV}")
								if [ ! -b "${REAL_LUKS_KEYDEV}" ]
								then
									KEYDEV_ERROR=1
									bad_msg "Removable device ${LUKS_KEYDEV} not found." ${CRYPT_SILENT}
									continue
								fi
								# continue otherwise will mount keydev which is mounted by bootstrap
								continue
							fi
						fi

						# At this point a device was recognized, now let's see if the key is there
						[ ! -d "${mntkey}" ] && mkdir -p "${mntkey}" >/dev/null 2>&1

						mount -n -o ro ${REAL_LUKS_KEYDEV} ${mntkey} >/dev/null 2>&1
						if [ "$?" != '0' ]
						then
							KEYDEV_ERROR=1
							bad_msg "Mounting of device ${REAL_LUKS_KEYDEV} failed." ${CRYPT_SILENT}
							continue
						else
							good_msg "Removable device ${REAL_LUKS_KEYDEV} mounted." ${CRYPT_SILENT}
							sleep 2
							# keyfile exists?
							if [ ! -e "${mntkey}${LUKS_KEY}" ]
							then
								umount -n "${mntkey}" >/dev/null 2>&1
								KEY_ERROR=1
								KEYDEV_ERROR=1
								bad_msg "Key {LUKS_KEY} on device ${REAL_LUKS_KEYDEV} not found." ${CRYPT_SILENT}
								continue
							fi
						fi
					fi
					# At this point a candidate key exists (either mounted before or not)
					good_msg "${LUKS_KEY} on device ${REAL_LUKS_KEYDEV} found" ${CRYPT_SILENT}

					if [ "$(echo ${LUKS_KEY} | grep -o '.gpg$')" = ".gpg" ]
					then
						if [ ! -x '/sbin/gpg' ]
						then
							bad_msg "GPG-encrypted key file provided but gpg program is missing. Was initramfs built without --gpg parameter?"
							bad_msg "Falling back to passphrase usage!"
						else
							[ -e /dev/tty ] && mv /dev/tty /dev/tty.org
							mknod /dev/tty c 5 1
							cryptsetup_options="${cryptsetup_options} -d -"
							gpg_cmd="/sbin/gpg --logger-file /dev/null --quiet --decrypt ${mntkey}${LUKS_KEY} |"
						fi
					else
						cryptsetup_options="${cryptsetup_options} -d ${mntkey}${LUKS_KEY}"
					fi
				fi
				# At this point, keyfile or not, we're ready!
				crypt_filter "${gpg_cmd}cryptsetup ${cryptsetup_options} luksOpen ${LUKS_DEVICE} ${LUKS_NAME}"
				crypt_filter_ret=$?

				[ -e /dev/tty.org ] \
					&& rm -f /dev/tty \
					&& mv /dev/tty.org /dev/tty

				if [ ${crypt_filter_ret} -eq 0 ]
				then
					touch "${OPENED_LOCKFILE}"
					good_msg "LUKS device ${LUKS_DEVICE} opened" ${CRYPT_SILENT}
					break
				elif [ ! -e "${OPENED_LOCKFILE}" ]
				then
					bad_msg "Failed to open LUKS device ${LUKS_DEVICE}" ${CRYPT_SILENT}
					DEV_ERROR=1
					KEY_ERROR=1
					KEYDEV_ERROR=1
				fi
			fi
		fi
	done
	umount "${mntkey}" >/dev/null 2>&1
	rmdir -p "${mntkey}" >/dev/null 2>&1
}

iface_name() {
	local ifname="${1}"

	if echo "${ifname}" | grep -qE ':|-'
	then
		local interface=
		local mac="$(echo "${ifname}" | sed 'y/ABCDEF-/abcdef:/')"

		for interface in /sys/class/net/*
		do
			if [ $(cat ${interface}/address) = "${mac}" ]
			then
				echo ${interface##*/}
				return
			fi
		done
	else
		echo "${ifname}"
	fi
}

start_network() {
	# Load network modules only when we need them to avoid possible
	# firmware problems for people not using network that early
	MY_HWOPTS=net load_modules

	# At least gk.net.iface can only be processed after sysfs was
	# mounted.
	local x=
	for x in ${CMDLINE}
	do
		case "${x}" in
			ip=*)
				IP=${x#*=}
			;;
			gk.net.dhcp.retries=*)
				local tmp_n_retries=${x#*=}
				if is_int "${tmp_n_retries}"
				then
					GK_NET_DHCP_RETRIES=${tmp_n_retries}
				else
					warn_msg "'${x}' does not look like a valid number -- will keep using default value ${GK_NET_DHCP_RETRIES}!"
				fi
				unset tmp_n_retries
			;;
			gk.net.gw=*)
				GK_NET_GW=${x#*=}
			;;
			gk.net.iface=*)
				GK_NET_IFACE=${x#*=}
			;;
			gk.net.routes=*)
				GK_NET_ROUTES=${x#*=}
			;;
			gk.net.timeout.interface=*)
				local tmp_interface_timeout=${x#*=}
				if is_int "${tmp_interface_timeout}"
				then
					GK_NET_TIMEOUT_INTERFACE=${tmp_interface_timeout}
				else
					warn_msg "'${x}' does not look like a valid number -- will keep using default value ${GK_NET_TIMEOUT_INTERFACE}!"
				fi
				unset tmp_interface_timeout
			;;
			gk.net.timeout.dad=*)
				local tmp_dad_timeout=${x#*=}
				if is_int "${tmp_dad_timeout}"
				then
					GK_NET_TIMEOUT_DAD=${tmp_dad_timeout}
				else
					warn_msg "'${x}' does not look like a valid number -- will keep using default value ${GK_NET_TIMEOUT_DAD}!"
				fi
				unset tmp_dad_timeout
			;;
			gk.net.timeout.deconfiguration=*)
				local tmp_deconfiguration_timeout=${x#*=}
				if is_int "${tmp_deconfiguration_timeout}"
				then
					GK_NET_TIMEOUT_DECONFIGURATION=${tmp_deconfiguration_timeout}
				else
					warn_msg "'${x}' does not look like a valid number -- will keep using default value ${GK_NET_TIMEOUT_DECONFIGURATION}!"
				fi
				unset tmp_deconfiguration_timeout
			;;
			gk.net.timeout.dhcp=*)
				local tmp_dhcp_timeout=${x#*=}
				if is_int "${tmp_dhcp_timeout}"
				then
					GK_NET_TIMEOUT_DHCP=${tmp_dhcp_timeout}
				else
					warn_msg "'${x}' does not look like a valid number -- will keep using default value ${GK_NET_TIMEOUT_DHCP}!"
				fi
				unset tmp_dhcp_timeout
			;;
		esac
	done

	local interface_identifier=device
	if echo "${GK_NET_IFACE}" | grep -qE ':|-'
	then
		interface_identifier=mac
		good_msg_n "Waiting for interface with MAC address ${GK_NET_IFACE} ..."
	else
		good_msg_n "Waiting for interface ${GK_NET_IFACE} ..."
	fi

	local tmp_interface=
	local have_interface=0
	local interface_time_waited=0
	local interface_timeout_100msec_modulo=
	local interface_timeout && let interface_timeout=$(date +%s)+1
	[ -n "${GK_NET_TIMEOUT_INTERFACE}" -a "${GK_NET_TIMEOUT_INTERFACE}" -gt 0 ] && let interface_timeout=${interface_timeout}+${GK_NET_TIMEOUT_INTERFACE}-1

	while [ "${have_interface}" != '1' -a $(date +%s) -le ${interface_timeout} ]
	do
		tmp_interface=$(iface_name "${GK_NET_IFACE}")
		if [ -n "${tmp_interface}" ]
		then
			# We got at least something to probe
			if [ -d "/sys/class/net/${tmp_interface}" ]
			then
				GK_NET_IFACE="${tmp_interface}"
				have_interface=1
				break
			fi
		fi

		if [ "${have_interface}" != '1' ]
		then
			let interface_time_waited=${interface_time_waited}+1
			sleep 0.1s

			let interface_timeout_100msec_modulo=${interface_time_waited}%10
			if [ ${interface_timeout_100msec_modulo} = 0 ]
			then
				printf "."
			fi
		fi
	done

	echo

	if [ "${have_interface}" != '1' ]
	then
		# Timeout!
		if [ "${interface_identifier}" = 'mac' ]
		then
			bad_msg "Interface with MAC address ${GK_NET_IFACE} not found!"
		else
			bad_msg "Interface ${GK_NET_IFACE} not found!"
		fi

		warn_msg "Will not try to start network ..."
		return 1
	fi

	if [ -z "${IP}" -o "${IP}" = 'dhcp' ]
	then
		good_msg "Bringing up interface ${GK_NET_IFACE} using dhcp ..." ${QUIET}
		busybox udhcpc -i "${GK_NET_IFACE}" -n -t ${GK_NET_DHCP_RETRIES} -T ${GK_NET_TIMEOUT_DHCP} -R -p "${GK_NET_DHCP_PIDFILE}"
		if [ $? -ne 0 ]
		then
			bad_msg "Failed to start udhcpc for interface ${GK_NET_IFACE}!"
			return 1
		fi
	else
		good_msg "Bringing up interface ${GK_NET_IFACE} ..." ${QUIET}
		ip link set "${GK_NET_IFACE}" up

		good_msg "Setting address '${IP}' on ${GK_NET_IFACE} ..." ${QUIET}
		ip addr add "${IP}" dev "${GK_NET_IFACE}"

		if [ -n "${GK_NET_ROUTES}" ]
		then
			local route=
			for route in ${GK_NET_ROUTES}
			do
				good_msg "Adding additional route '${route}' on ${GK_NET_IFACE} ..." ${QUIET}
				ip route add "${route}" dev "${GK_NET_IFACE}"
			done
		fi

		if [ -n "${GK_NET_GW}" ]
		then
			good_msg "Adding default route via '${GK_NET_GW}' on ${GK_NET_IFACE} ..." ${QUIET}
			ip route add default via "${GK_NET_GW}" dev "${GK_NET_IFACE}"
		fi
	fi

	touch "${GK_NET_LOCKFILE}"
}

kill_network() {
	if [ -s "${GK_NET_DHCP_PIDFILE}" ]
	then
		good_msg "Stopping udhcpc ..."
		kill $(cat "${GK_NET_DHCP_PIDFILE}")
	fi

	if [ ! -d "/sys/class/net/${GK_NET_IFACE}" ]
	then
		warn_msg "Interface ${GK_NET_IFACE} not found. Already down?"
		return
	fi

	# If we are too quick and interface is still configuring IPv6
	# waiting for DAD to complete due to received IPv6 RA, we have to
	# wait.
	# If we don't wait, ip command will bring down interface for a
	# moment but it will return to up state once DAD is completed which
	# will cause trouble with real system which is expecting an unused
	# interface.
	if ipv6_tentative
	then
		[ -z "${QUIET}" ] && \
		printf "%b" "${WARN}**${NORMAL}${BOLD} Waiting for tentative IPv6 addresses to complete DAD ${NORMAL}..."

		local dad_timeout=10
		while [ ${dad_timeout} -gt 0 ]
		do
			ipv6_tentative || break
			sleep 1
			: $(( dad_timeout -= 1 ))
			[ -z "${QUIET}" ] && \
			printf "."
		done

		echo ""

		if [ ${dad_timeout} -le 0 ]
		then
			bad_msg "DAD still not completed after ${GK_NET_TIMEOUT_DAD} seconds!"
		fi
	fi

	[ -z "${QUIET}" ] && \
	printf "%b" "${GOOD}>>${NORMAL}${BOLD} Bringing down interface ${GK_NET_IFACE} ${NORMAL}..."

	local deconfiguration_timeout=${GK_NET_TIMEOUT_DECONFIGURATION}
	while [ ${deconfiguration_timeout} -gt 0 ]
	do
		ip addr flush dev "${GK_NET_IFACE}"
		ip route flush dev "${GK_NET_IFACE}"
		ip link set "${GK_NET_IFACE}" down
		if grep -q "down" "/sys/class/net/${GK_NET_IFACE}/operstate" 2>/dev/null
		then
			break
		fi
		sleep 1
		: $(( deconfiguration_timeout -= 1 ))
		[ -z "${QUIET}" ] && \
		printf "."
	done

	echo ""

	if [ ${deconfiguration_timeout} -le 0 ]
	then
		bad_msg "Failed to bring down interface ${GK_NET_IFACE} within ${GK_NET_TIMEOUT_DECONFIGURATION} seconds!"
		return
	fi

	rm "${GK_NET_LOCKFILE}"
}

ipv6_tentative() {
	if ip -family inet6 addr show dev "${GK_NET_IFACE}" 2>/dev/null | grep -q " tentative "
	then
		return 0
	else
		return 1
	fi
}

start_LUKS() {
	# if key is set but neither ssh enabled or key device is given, find
	# the key device

	[ -n "${CRYPT_ROOT_KEY}" ] && [ -z "${CRYPT_ROOT_KEYDEV}" ] \
		&& sleep 6 && bootstrapKey "ROOT"

	if [ -n "${CRYPT_ROOT}" ]
	then
		openLUKS "root"
		if [ -n "${REAL_ROOT}" ]
		then
			# Rescan volumes
			start_volumes
		else
			REAL_ROOT="/dev/mapper/root"
		fi
	fi

	# same for swap, but no need to sleep if root was unencrypted
	[ -n "${CRYPT_SWAP_KEY}" ] && [ -z "${CRYPT_SWAP_KEYDEV}" ] \
		&& { [ -z "${CRYPT_ROOT}" ] && sleep 6; bootstrapKey "SWAP"; }

	if [ -n "${CRYPT_SWAP}" ]
	then
		openLUKS "swap"
		if [ -z "${REAL_RESUME}" ]
		then
			# Resume from swap as default
			REAL_RESUME="/dev/mapper/swap"
		fi
	fi
}

start_sshd() {
	if [ -s "${GK_SSHD_PIDFILE}" ]
	then
		# Already running
		return
	fi

	if [ ! -f "${GK_NET_LOCKFILE}" ]
	then
		warn_msg "Network not started; Not starting sshd ..."
		return
	fi

	if [ ! -x "/usr/sbin/dropbear" ]
	then
		bad_msg "/usr/sbin/dropbear not found! Did you call genkernel with --ssh parameter?"
		return
	fi

	# setup environment variables for the ssh login shell
	local varname= varvalue=
	touch "${CRYPT_ENV_FILE}"
	for varname in CRYPT_ROOT CRYPT_ROOT_TRIM CRYPT_SILENT CRYPT_SWAP DEBUG
	do
		eval varvalue=\$${varname}
		echo "${varname}=${varvalue}" >> "${CRYPT_ENV_FILE}"
	done

	touch /var/log/lastlog

	good_msg "Starting dropbear sshd ..." ${QUIET}
	/usr/sbin/dropbear -p ${GK_SSHD_PORT} -R -P "${GK_SSHD_PIDFILE}" 2>/var/log/dropbear.log
	test_success "Failed to start dropbear"
}

wait_sshd() {
	if [ -z "${GK_SSHD_WAIT}" -o "${GK_SSHD_WAIT}" = '0' ]
	then
		return
	fi

	if [ -f "${GK_SSHD_LOCKFILE}" -o ! -s "${GK_SSHD_PIDFILE}" ]
	then
		return
	fi

	printf "%b" "${GOOD}>>${NORMAL}${BOLD} gk.sshd.wait set; Waiting ${GK_SSHD_WAIT} seconds for SSH connection ${NORMAL}..."

	local ssh_timeout=${GK_SSHD_WAIT}
	while [ ${ssh_timeout} -gt 0 ]
	do
		if [ -f "${GK_SSHD_LOCKFILE}" ]
		then
			echo ""
			last -W | head -n 3 2>/dev/null
			break
		fi
		sleep 1
		: $(( ssh_timeout -= 1 ))
		printf "."
	done

	echo ""
}

kill_sshd() {
	if [ -s "${GK_SSHD_PIDFILE}" ]
	then
		good_msg "Stopping dropbear sshd ..." ${QUIET}
		kill $(cat "${GK_SSHD_PIDFILE}")
	fi
}

cleanup() {
	if [ -f "${GK_NET_LOCKFILE}" ]
	then
		if [ -f "${GK_SSHD_LOCKFILE}" ]
		then
			warn_msg "The lockfile at '${GK_SSHD_LOCKFILE}' exists."
			warn_msg "The boot process will be paused until the lock is removed."
			while true
			do
				if [ -f "${GK_SSHD_LOCKFILE}" ]
				then
					sleep 1
				else
					break
				fi
			done
		fi
	fi

	kill_sshd

	# Ensure that we terminated any existing connection
	pkill -9 dropbear >/dev/null 2>&1

	if [ -f "${GK_NET_LOCKFILE}" ]
	then
		kill_network
	fi
}

sdelay() {
	# Sleep a specific number of seconds if SDELAY is set
	if [ -n "${SDELAY}" ]
	then
		good_msg_n "Waiting ${SDELAY} seconds ..."
		while [ ${SDELAY} -gt 0 ]
		do
			let SDELAY=${SDELAY}-1
			sleep 1
			printf "."
		done
		echo
	elif [ "${CDROOT}" = '1' ]
	then
		good_msg 'Hint: Use scandelay[=seconds] if your live medium is slow and boot fails'
	fi
}

quiet_kmsg() {
	# if QUIET is set make the kernel less chatty
	[ -n "${QUIET}" ] && echo '0' > /proc/sys/kernel/printk
}

verbose_kmsg() {
	# if QUIET is set make the kernel less chatty
	[ -n "${QUIET}" ] && echo '6' > /proc/sys/kernel/printk
}

cdupdate() {
	if [ "${CDROOT}" = '1' ]
	then
		cdupdate_path=''
		for p in /${NEW_ROOT}/${CDROOT_PATH}/ /${CDROOT_PATH}/
		do
			[ -x "${p}/cdupdate.sh" ] && cdupdate_path="${p}/cdupdate.sh" && break
		done

		if [ -n "${cdupdate_path}" ]
		then
			good_msg "Running cdupdate.sh (${cdupdate_path})"
			${cdupdate_path}
			if [ "$?" != '0' ]
			then
				bad_msg "Executing cdupdate.sh failed!"
				run_shell
			fi
		else
			good_msg 'No cdupdate.sh script found, skipping ...'
		fi
	fi
}

setup_btrfsctl() {
	# start BTRFS volume detection, if available
	[ -x /sbin/btrfsctl ] && /sbin/btrfsctl -a
}

setup_md_device() {
	local device

	[ -z "$1" ] && device="${REAL_ROOT}" || device="$1"
	[ -z "${device}" ] && return # LiveCD

	if [ $(echo ${device}|sed -e 's#\(luks:\)\?\(/dev/md\)[[:digit:]]\+#\2#') = "/dev/md" ]
	then
		good_msg 'Detected real_root as a md device. Setting up the device node ...'
		MD_NUMBER=$(echo ${device}|sed -e 's#\(luks:\)\?/dev/md\([[:digit:]]\+\)#\2#')
		if [ ! -e /dev/md${MD_NUMBER} ]
		then
			mknod /dev/md${MD_NUMBER} b 9 ${MD_NUMBER} >/dev/null 2>&1
			[ $? -ne 0 ] && bad_msg "Creation of /dev/md${MD_NUMBER} failed ..."
		fi
		mdstart ${MDPART} /dev/md${MD_NUMBER}
	fi
}

rundebugshell() {
	if [ -n "${DEBUG}" ]
	then
		good_msg 'Starting debug shell as requested by "debug" option.'
		good_msg "Stopping by: ${1}"
		run_shell
	fi
}

do_resume() {
	if [ -d /proc/suspend2 -o -d /sys/power/suspend2 -o -d /sys/power/tuxonice ]
	then
		tuxonice_resume
	else
		swsusp_resume
	fi
}

swsusp_resume() {
	# determine swap resume partition
	local device=$(ls -lL "${REAL_RESUME}" | sed 's/\  */ /g' | cut -d \  -f 5-6 | sed 's/,\ */:/')
	[ -f /sys/power/resume ] && echo "${device}" > /sys/power/resume
}

tuxonice_resume() {
	local splash_theme
	if grep "splash=" /proc/cmdline >/dev/null 2>&1
	then
		splash_theme=$(cat /proc/cmdline | sed 's/.*splash=/splash=/' | sed 's/ .*//' | sed 's/.*theme://' | sed 's/,.*//')
	fi

	local tuxonice_userui_program="/sys/power/tuxonice/user_interface/program"
	local tuxonice_do_resume="/sys/power/tuxonice/do_resume"
	local tuxonice_resumedev="/sys/power/tuxonice/resume"
	local tuxonice_replace_swsusp="/sys/power/tuxonice/replace_swsusp"

	#
	# Backward compatibility
	#
	if [ -e /sys/power/suspend2 ]
	then
		tuxonice_userui_program="/sys/power/suspend2/user_interface/program"
		tuxonice_do_resume="/sys/power/suspend2/do_resume"
		tuxonice_resumedev="/sys/power/suspend2/resume"
		tuxonice_replace_swsusp="/sys/power/suspend2/replace_swsusp"
	elif [ -e /proc/suspend2 ]
	then
		tuxonice_userui_program="/proc/suspend2/userui_program"
		tuxonice_do_resume="/proc/suspend2/do_resume"
		tuxonice_resumedev="/proc/suspend2/resume"
		tuxonice_replace_swsusp="/proc/suspend2/replace_swsusp"
	fi

	# if 'use_swsusp' is given, use swsusp instead
	if grep "use_swsusp" /proc/cmdline >/dev/null 2>&1
	then
		echo 0 > ${tuxonice_replace_swsusp}
		swsusp_resume
		return
	fi

	modules_scan tuxonice

	# we both configure tuxonice and activate resuming,
	# however the kernel will resume only if an image is found

	if ! grep suspend_noui /proc/cmdline >/dev/null 2>&1
	then
		which suspend2ui_text >/dev/null 2>&1 && which suspend2ui_text > "${tuxonice_userui_program}"
		which tuxoniceui_text >/dev/null 2>&1 && which tuxoniceui_text > "${tuxonice_userui_program}"

		if [ -n "${splash_theme}" ]
		then
			ln -s /etc/splash/${splash_theme} /etc/splash/suspend2
			ln -s /etc/splash/${splash_theme} /etc/splash/tuxonice

			which suspend2ui_fbsplash >/dev/null 2>&1 && which suspend2ui_fbsplash > "${tuxonice_userui_program}"
			which tuxoniceui_fbsplash >/dev/null 2>&1 && which tuxoniceui_fbsplash > "${tuxonice_userui_program}"
		fi

	fi
	echo "${REAL_RESUME}" > "${tuxonice_resumedev}"
	echo > "${tuxonice_do_resume}"
}

find_loop() {
	for loop in ${LOOPS}
	do
		if [ -e "${CDROOT_PATH}""${loop}" ]
		then
			LOOP="${loop}"
		fi
	done
}

find_looptype() {
	LOOPTYPE="${LOOP##*.}"
	[ "${LOOPTYPE}" = "loop" ] && LOOPTYPE="normal"
	[ "${LOOP}" = "/zisofs" ] && LOOPTYPE="${LOOP#/}"
	[ -z "${LOOPTYPE}" ] && LOOPTYPE="noloop"
}

getdvhoff() {
	echo $(( $(hexdump -n 4 -s $((316 + 12 * $2)) -e '"%i"' $1) * 512))
}

setup_squashfs_aufs() {
	# Setup aufs directories and vars
	aufs_rw_branch=/mnt/aufs-rw-branch aufs_ro_branch=/mnt/livecd

	for dir in ${aufs_rw_branch} ${aufs_ro_branch}
	do
		[ ! -d "${dir}" ] && mkdir -p "${dir}"
	done

	good_msg "Loading aufs module ..."
	modprobe aufs >/dev/null 2>&1
	checkfs aufs

	mount -t squashfs -o loop,ro "${CDROOT_PATH}/${LOOPEXT}${LOOP}" "${aufs_ro_branch}"
	mount -t tmpfs none "${aufs_rw_branch}"
	mount -t aufs -o "br:${aufs_rw_branch}:${aufs_ro_branch}" aufs "${NEW_ROOT}"
}

setup_unionfs() {
	local rw_dir=$1
	local ro_dir=$2
	if [ "${USE_UNIONFS_NORMAL}" = '1' ]
	then
		# Directory used for rw changes in union mount filesystem
		UNION=/union
#		MEMORY=/memory
#		if [ -z "${UID}" ]
#		then
#			CHANGES=${MEMORY}/unionfs_changes/default
#		else
#			CHANGES=${MEMORY}/unionfs_changes/${UID}
#		fi

#		mkdir -p ${MEMORY}
		mkdir -p ${UNION}
		good_msg "Loading fuse module"
		modprobe fuse >/dev/null 2>&1
#		 if [ -n "${UNIONFS}" ]
#		 then
#			 CHANGESDEV=${UNIONFS}
#			 good_msg "mounting ${CHANGESDEV} to ${MEMORY} for unionfs support"
#			 mount -t auto ${CHANGESDEV} ${MEMORY}
#			 # mount tmpfs only in the case when changes= boot parameter was
#			 # empty or we were not able to mount the storage device
#			 ret=$?
#			 if [ ${ret} -ne 0 ]
#			 then
#				 bad_msg "mount of ${CHANGESDEV} failed falling back to ramdisk based unionfs"
#				 mount -t tmpfs tmpfs ${MEMORY}
#			 fi
#			 if [ "${CDROOT}" -eq '1' -a ! -f ${MEMORY}/livecd.unionfs ]
#			 then
#				 umount ${MEMORY}
#				 bad_msg "failed to find livecd.unionfs file on ${CHANGESDEV}"
#				 bad_msg "create a livecd.unionfs file on this device if you wish to use it for unionfs"
#				 bad_msg "falling back to ramdisk based unionfs for safety"
#				 mount -t tmpfs tmpfs ${MEMORY}
#			 fi
#		 else
#			 good_msg "Mounting ramdisk to ${MEMORY} for unionfs support..."
#			 mount -t tmpfs tmpfs ${MEMORY}
#		 fi

		mkdir /tmp
		mkdir -p ${UNION}
#		mkdir -p ${CHANGES}
#		mount -t unionfs -o dirs=${CHANGES}=rw unionfs ${UNION}
		good_msg "Creating union mount"
		unionfs -o allow_other,cow,noinitgroups,suid,dev,default_permissions,use_ino ${rw_dir}=RW:${ro_dir}=RO ${UNION} 2>/dev/null
		ret=$?
		if [ ${ret} -ne 0 ]
		then
			bad_msg "Can't setup union mount!"
			USE_UNIONFS_NORMAL=0
		fi
		[ ! -d "${NEW_ROOT}${CDROOT_PATH}" ] && mkdir -p "${NEW_ROOT}${CDROOT_PATH}"
		mount --bind "${CDROOT_PATH}" "${NEW_ROOT}${CDROOT_PATH}"
	else
		USE_UNIONFS_NORMAL=0
	fi
}

get_mounts_list() {
	awk '
		/^[[:blank:]]*#/ { next }
		{ print $1 }
		' ${NEW_ROOT}/etc/initramfs.mounts
}

get_mount_fstype() {
	[ -e "${NEW_ROOT}"/etc/fstab ] || return 1
	awk -v fs="$1" '
		/^[[:blank:]]*#/ { next }
		$2 == fs { print $3 }
		' ${NEW_ROOT}/etc/fstab
}

get_mount_options() {
	[ -e "${NEW_ROOT}"/etc/fstab ] || return 1
	awk -v fs="$1" '
		/^[[:blank:]]*#/ { next }
		$2 == fs { print $4 }
		' ${NEW_ROOT}/etc/fstab
}

get_mount_device() {
	[ -e "${NEW_ROOT}"/etc/fstab ] || return 1
	awk -v fs="$1" '
		/^[[:blank:]]*#/ { next }
		$2 == fs { print $1 }
		' ${NEW_ROOT}/etc/fstab
}

# If the kernel is handed a mount option is does not recognize, it WILL fail to
# mount. util-linux handles auto/noauto, but busybox passes it straight to the kernel
# which then rejects the mount.
# To make like a little easier, busybox mount does not care about leading,
# trailing or duplicate commas.
strip_mount_options() {
	sed -r \
		-e 's/(,|^)(no)?auto(,|$)/,/g' \
		-e 's/(,|^)iversion(,|$)/,/g'
}

checkfs() {
	if [ -r "/proc/filesystems" ]
	then
		if grep -qs "$1" /proc/filesystems
		then
			return 0
		fi
	fi

	warn_msg "No ${1} support listed in /proc/filesystems"
	warn_msg "${1} is not likely to work on this medium"

	return 1
}