aboutsummaryrefslogtreecommitdiff
path: root/knoppix/860/init
blob: 7494e38f515d038de53ff2d533a7c09b75d751d6 (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
#!/bin/sh
#
# Microknopppix busybox-based initramfs bootscript
# (C) 2015 by Klaus Knopper <knoppix@knopper.net>
# LICENSE: GPL V2

# Its purpose: 
# 1. Mounting CD, DVD, Flashdisk or network drive,
# 2. unifying read-only compressed file system and ramdisk or file overlay,
# 3. give control to the real sysv init, which then continues to work like
#    we booted from a single disk partition.

# Preconditions:
# - Kernel contains all drivers necessary to mount initial media
# - cloop.ko and aufs.ko are either kernel builtins, or located as modules
#   in /mnt-system/"$knoppix_dir"/modules

DISTRO="Knoppix 8.6"
KVERSION="8.6.0-2019-08-08"
# KVERS=$(echo ${KVERSION//.} | cut -b -3) # ... cannot do
KVERS='860' # Short (hardcode)

# Reset fb color mode
RESET="]R"
# ANSI COLORS
# Erase to end of line
CRE="
"
# Clear entire screen
CLEAR=""
# Normal color
NORMAL=""
# RED: Failure or error message
RED=""
# GREEN: Success message
GREEN=""
# YELLOW: Descriptions
YELLOW=""
# BLUE: System mesages
BLUE=""
# MAGENTA: Found devices or drivers
MAGENTA=""
# CYAN: Questions
CYAN=""
# BOLD WHITE: Hint
WHITE=""
# Start Unicode
START_UNICODE="%G"

# Directory where all Knoppix files are located (except for kernel and initrd)
# This way, you can have multiple Knoppix versions on the same media, and
# specify which one to load by "knoppix knoppix_dir=directory"
[ -n "$knoppix_dir" ] || knoppix_dir="KNOPPIX"
[ -z "$root" -a -n "$fromhd" ] && root="$fromhd"

# This is set by findknoppix()
ROOTDEV=""

# Early Localization
case "$lang" in
 de*) 
      export LANG="de_DE.UTF-8" LANGUAGE="de_DE.UTF-8" LC_MESSAGES="de_DE.UTF-8"
      WELCOME="${WHITE}Willkommen zu $DISTRO basierend auf MICRO${CYAN}K${MAGENTA}N${YELLOW}O${BLUE}P${RED}P${GREEN}I${WHITE}X!${NORMAL}"
      SEARCHINGFOR="Suche nach"
      FOUNDAT="gefunden in"
      WAITFORUSB="Warte (USB)..."
      STARTLIVE=">>> Starte im Live-Modus.                                              <<<\n>>> Bitte den Datenträger bis zum Herunterfahren nicht mehr entfernen! <<<"
      CREATEIMG1="Auf diesem Datenträger ist noch keine Datei zum Speichern der persönlichen Daten vorhanden. Wenn gewünscht, bitte Größe in MB angeben (mindestens 200, frei: "
      CREATEIMG2=").

Bitte das Feld einfach leer lassen, wenn keine Datei zum Speichern angelegt werden soll."
      NOTFOUND="Konnte Disk nicht nach /mnt-system mounten. Starte debugging Shell."
      NOKNOPPIX="Konnte /mnt-system/$knoppix_dir/KNOPPIX nicht mounten. Starte debugging Shell..."
      COPYING="Kopiere Daten, ${WHITE}Leertaste${CYAN} zum Überspringen."
      CHECKING="Prüfe"
      FAILED="Fehler!"
      CANCELLED="Abbruch"
      NOSPACE="Nicht genügend freier Platz vorhanden."
      ASKREBOOT="Start fehlgeschlagen, Eingabetaste zum Neustart."
      CONTINUE="Trotzdem weitermachen? [j/N] "
      BROKENIMAGE="Komprimiertes KNOPPIX Image ist kaputt"
      ALLOK="Alle Dateien in Ordnung."
      ON="auf"
      QUESTION_ENCRYPT="Soll das Image mit AES256 (=Advanced Encryption Standard 256bit, s.a. http://csrc.nist.gov/encryption/aes/) verschlüsselt werden?\n\nHierzu ist die Eingabe eines Passwortes beim Einrichten sowie beim Einbinden des Image beim Systemstart erforderlich.\n\nOhne Kenntnis des korrekten Passwortes ist der Zugriff auf die Daten nicht möglich, dadurch sind die möglicherweise sensiblen Daten einerseits bei Verlust des Datenträgers vor unbefugtem Zugriff geschützt, andererseits sind sie bei vergessenem Passwort auch nicht mehr vefügbar."
      ENCRYPT="Verschlüsseln"
      NO_ENCRYPT="Nicht verschlüsseln"
      QUESTION_PASSWORD1="AES256 Verschlüsselungs Passwort (mindestens 8 Zeichen):"
      QUESTION_PASSWORD2="Bitte Passwort zur Sicherheit noch einmal eingeben:"
      PASSWORDS_NOMATCH="Die beiden Passwörter stimmen nicht überein oder sind zu kurz.\nBitte noch einmal versuchen."
      CREATING="Lege Datenbereich an, dies kann sehr lange dauern..."
      USING="Verwende"
      UPDATING="Installiere Update"
      ASPERSISTENT="als persistentes Image."
      DOESNOTEXIST="existiert nicht."
      EXPANDING="Expandiere"
      TOOSMALL="Partition ist zu klein (<400MB)"
      ;;
   *) WELCOME="${WHITE}Welcome to $DISTRO based on MICRO${CYAN}K${MAGENTA}N${YELLOW}O${BLUE}P${RED}P${GREEN}I${WHITE}X!${NORMAL}"
      SEARCHINGFOR="Searching for"
      FOUNDAT="found at"
      WAITFORUSB="Waiting (USB)..."
      STARTLIVE=">>> Starting in Live-Mode.                                             <<<\n>>> Please do not remove medium until shutdown!                        <<<"
      CREATEIMG1="No file for saving personal data has been created on this device yet. If you wish to do so now, please enter desired size in MB (minimum 200, free: "
      CREATEIMG2=").

If you don't want to create a file for saving right now, just leave the field empty."
      NOTFOUND="Could not mount disk to /mnt-system. Starting debugging Shell..."
      NOKNOPPIX="Could not mount /mnt-system/$knoppix_dir/KNOPPIX. Starting debugging Shell..."
      COPYING="Copying data, press ${WHITE}space${CYAN} to skip."
      CHECKING="Checking"
      FAILED="Failed!"
      CANCELLED="Cancelled"
      NOSPACE="Not enough free space available."
      ASKREBOOT="Start failed, press enter to reboot."
      CONTINUE="Continue anyways? [y/N] "
      BROKENIMAGE="Compressed KNOPPIX image is broken"
      ALLOK="All files OK."
      ON="on"
      QUESTION_ENCRYPT="Would you like to encrypt the image using AES256 (=Advanced Encryption Standard 256bit, http://csrc.nist.gov/encryption/aes/)?\n\nFor this type of encryption, entering a password when creating as well as mounting the image at system start is necessary.\n\nWithout knowing this password, reading saved data is not possible. Because of that, encrypted data is still still safe against unauthorized access in case the storage device containig the data gets lost or stolen. On the other hand, all saved data is inaccessible if you forget the password, there is no way to recover."
      ENCRYPT="Encrypt"
      NO_ENCRYPT="Don't encrypt"
      QUESTION_PASSWORD1="AES256 Encryption Key (minimum 8 chars):"
      QUESTION_PASSWORD2="Please enter the same password again, just to be sure:"
      PASSWORDS_NOMATCH="Passwords are not identical, or just too short.\nPlease try again."
      CREATING="Creating space for data, this can take a very long time..."
      USING="Using"
      UPDATING="Installing update"
      ASPERSISTENT="as persistent image."
      DOESNOTEXIST="does not exist."
      TOOSMALL="partition is too small (<400M)"
      EXPANDING="Expanding"
      export LANG="C" LANGUAGE="C" LC_MESSAGES="C"
      ;;
esac

bailout(){
 [ "$1" = "0" ] && return 0
 reboot -f
 sleep 1337
}

# Check boot commandline for specified option
checkbootparam(){
 local i
 for i in $CMDLINE; do
  case "$i" in $1|$1=*) return 0;; esac
 done
 return 1
}

# like echo, but only if no "splash" boot option is present
message(){
 [ -n "$SPLASH" ] || echo "$@"
}

debugshell(){
 [ -n "$1" ] && echo "$1"
 setkeyboard
 /bin/busybox sh
 bailout $?
}

trymount(){
 local rc="1" rw="$RW"
 read_only "$1" && rw="ro"
 # Try to be quick, and probe the "most likely" file systems first
 mount -t vfat -o "$rw",umask=000,shortname=winnt "$1" "$2" || \
  mount -t iso9660 -o ro "$1" "$2" || \
   ntfs-3g -o "$rw",umask=000,force "$1" "$2" || \
    mount -t reiserfs -o "$rw" "$1" "$2" || \
     mount -t ext4 -o "$rw" "$1" "$2" || \
      mount -t ext3 -o "$rw" "$1" "$2" || \
       mount -t ext2 -o "$rw" "$1" "$2"
 rc="$?"
 # Still no luck? Try everything else that the (static) kernel supports
 if [ "$rc" != 0 ]; then
  local fs
  for fs in `awk '!/^nodev/{print $1}' /proc/filesystems 2>&1`; do
   case "$fs" in
    ext[234]|reiserfs|ntfs|fuse*|*fat|iso9660) ;; # Already did that
    *) mount -t "$fs" -o "$rw" "$1" "$2"; rc="$?";;
   esac
   [ "$rc" = "0" ] && break
  done
 fi
 return "$rc"
}

# findknoppix devices...
findknoppix(){
 local dev firstdev="" kvers=""
 for dev in "$@"; do
  [ -b "$dev" ] || continue
  message -n -e "\r${CRE}${BLUE}${SEARCHINGFOR} $DISTRO in: ${MAGENTA}$dev${NORMAL}   "
  trymount "$dev" /mnt-system >/dev/null 2>&1 || continue
  if [ -r /mnt-system/"$knoppix_dir"/KNOPPIX ]; then
   [ -r /mnt-system/"$knoppix_dir"/kversion ] || continue
   read kvers < /mnt-system/"$knoppix_dir"/kversion
   if [ "$KVERSION" = "$kvers" ]; then
    ROOTDEV="$dev"
    break
   fi
   [ -n "$firstdev" ] || firstdev="$dev"
  fi
  umount /mnt-system
  ROOTDEV=""
 done
 # Still no match found, and this is the last round
 if [ -z "$ROOTDEV" -a -n "$lastround" -a -n "$firstdev" ]; then
  trymount "$firstdev" /mnt-system && ROOTDEV="$firstdev"
 fi
 if [ -n "$ROOTDEV" ]; then
   message -e "\r${CRE}${GREEN}$DISTRO ${FOUNDAT}: ${MAGENTA}$ROOTDEV${NORMAL}       "
   return 0
 fi
 return 1
}

# Check if device containing Knoppix partition is read-only
read_only(){
 local dev="$1" disk=""
 [ -n "$dev" ] || dev="$ROOTDEV"
 # Read-only if boot option "ro" given
 checkbootparam ro && return 0
 # Read-only if not a block device
 [ -n "$dev" -a -b "$dev" ] || return 0
 # Remove /dev/ path
 dev="${dev#/dev/}"
 case "$dev" in
  sr*|scd*) disk="$dev" ;;
  mmcblk*)  disk="${dev%p*}" ;;
  *) # Normal disk, remove last two numbers if present
     disk="${dev%[1-9][0-9]}"; disk="${disk%[1-9]}" ;;
 esac
 # read-only if block device has "ro" set (switch, /sys/block/diskname/ro)
 [ "$(cat /sys/block/"$disk"/ro 2>/dev/null)" -gt 0 ] 2>/dev/null && return 0
 return 1
}

fork_copy(){
 local RC=0
 rm -f /tmp/log.txt /tmp/copy.done /tmp/copy.pid
 cp -rL /mnt-system/"$knoppix_dir"  /mnt-user/ >/tmp/log.txt 2>&1 &
 echo "$!" > /tmp/copy.pid
 wait
 RC="$?"
 if [ ! -r /tmp/copy.done ]; then
  [ "$RC" = "0" ] && echo "OK" >/tmp/copy.done || echo "ERROR" >/tmp/copy.done
 fi
}

printlive(){
 message -n -e "\r\033[J${WHITE}${STARTLIVE}${NORMAL}"
}

# print needed space in MB for copying KNOPPIX
getsize(){
 du -sm /mnt-system/"$knoppix_dir" 2>/dev/null | awk '{size+=$1}END{print size + 10}'
 return $?
}

# print free space on given mounted device
freespace(){
 df -m "$1" | awk '{size=$(NF-2)}END{print size}'
 return $?
}

# print size of mountpoint
getmpsize(){
 df -m "$1" | awk '{size=$(NF-4)}END{print size}'
 return $?
}

# copyto target_device
copyto(){
 local RC="0"
 local REQUIRED="$(getsize)"
 if [ "$1" = "tmpfs" ]; then
  mount -t tmpfs -o size="$REQUIRED"M,mode=0755,dev,suid,exec tmpfs /mnt-user
 else
  trymount "$1" /mnt-user >/dev/null 2>&1
 fi
 RC="$?"
 [ "$RC" = "0" ] || return "$RC"
 local FREE="$(freespace /mnt-user)"
 if [ "$REQUIRED" -gt "$FREE" ]; then
  echo "${RED}$NOSPACE${NORMAL}"
  umount -l /mnt-user
  return 1
 fi
 fork_copy &
 PID="$!"
 echo "${CYAN}$COPYING${NORMAL}"
 while [ ! -r /tmp/copy.done ]; do
  echo -n -e "\033[42;32m \033[0m"
  IFS= read -t 2 -n 1 key
  if [ "$?" = "0" -a "$key" = " " ]; then
   echo -n "${RED}$CANCELLED.${NORMAL}"
   read PID < /tmp/copy.pid 2>/dev/null
   [ -n "$PID" ] && kill "$PID"
   echo "ERROR" >"/tmp/copy.done"
   sleep 1
   printlive
  fi
 done
 echo ""
 [ -s /tmp/log.txt ] && cat /tmp/log.txt >&2
 rm -f /tmp/log.txt
 case "$(cat /tmp/copy.done; rm -f /tmp/copy.done)" in
  ERROR) rm -rf /mnt-user/"$knoppix_dir" 2>/dev/null; umount -l /mnt-user; touch /configmode-interrupted; return 1 ;;
  OK) umount /mnt-system; mount --move /mnt-user /mnt-system; return 0 ;;
 esac
}

ask_reboot(){
 local dummy
 read -p "${RED}$ASKREBOOT${NORMAL}" dummy
 bailout 1
}

# Check files in KNOPPIX/sha1sums
check_sha1sums(){
 local RC="0"
 local sum currentsum file relax
 [ -r /mnt-system/"$knoppix_dir"/sha1sums ] || return 0
 while read sum file; do
  file="$(echo "${file#\*}" | sed "s,KNOPPIX/,$knoppix_dir/,g")"
  [ -r /mnt-system/"$file" ] || continue
  echo -n "${CRE}${YELLOW}$CHECKING ${CYAN}$file...${NORMAL}"
  read currentsum relax <<EOT
$(sha1sum /mnt-system/"$file")
EOT
  [ "$currentsum" = "$sum" ] || { echo -e "${RED}$FAILED${NORMAL}"; RC="1"; }
 done </mnt-system/"$knoppix_dir"/sha1sums
 echo ""
 return "$RC"
}

# Turbo check: seek to compressed Knoppix file end and read 1k of data
# This function is purely informative and therefore void
check_knoppix(){
 ls -lL "$@" | awk '{print int($5 / 1024) " " $NF}' | while read size file; do
  if ! dd if="$file" bs=1024 skip="$(($size - 1))" count=1 2>/dev/null | wc -c | grep -q 1024; then
   echo "${RED}-------------------------------------------------------------------${NORMAL}"
   case "$LANG" in
    de*)
         echo "${RED}Die Datei $file (Größe ${size}kB) ist kaputt.${NORMAL}"
         echo "${RED}Vielleicht ein Brenn- oder Download-Fehler?${NORMAL}"
         echo "${RED}Bitte überprüfen Sie ggf. den Datenträger mit \"knoppix testcd\".${NORMAL}"
         echo "${RED}Warte 30 Sekunden vor dem Versuch, weiterzumachen...${NORMAL}"
	 ;;
    *)
         echo "${RED}The file $file (size ${size}kB) is broken.${NORMAL}"
         echo "${RED}Maybe a problem during download or burning?${NORMAL}"
         echo "${RED}You may want to check deeper using \"knoppix testcd\".${NORMAL}"
         echo "${RED}Waiting for 30 seconds before attempting to continue...${NORMAL}"
	 ;;
   esac
   echo "${RED}-------------------------------------------------------------------${NORMAL}"
   sleep 30
  fi
 done
}

load_modules(){
 local mod
 for mod in /modules/*.ko /modules/scsi/*.ko; do
  [ -r "$mod" -a ! -d /sys/module/"${mod%.ko}" ] && insmod "$mod" >/dev/null 2>&1
 done
}

setkeyboard(){
 [ -n "$keyboard" ] || keyboard="$lang"
 [ -n "$keyboard" -a -x "/KNOPPIX/bin/loadkeys" ] && runknoppixchroot /bin/loadkeys -q "$keyboard" >/dev/null 2>&1
}

# Main

# Clean input/output
exec >/dev/console </dev/console 2>&1

mount -t proc proc /proc
echo "0" >/proc/sys/kernel/printk

[ -r /etc/mtab ] && ln -snf /proc/mounts /etc/mtab

read CMDLINE </proc/cmdline

RW="rw"
checkbootparam "forensic" && RW="ro"

if checkbootparam "splash" && ! checkbootparam "debug"; then
 SPLASH="true"
fi

mount -t sysfs sysfs /sys

# Set console unicode-clean
echo -n "$START_UNICODE"

# Since we now have to deal with kernel mode settings, opposed to vesafb,
# we need to clear the screen on our own, eventually...

# Clear from line 5 (so there is space for the penguins)
case "$CMDLINE" in
 *\ vga=[0-9]*|*debug*|*\ splash*) true;; *) echo -n "";;
esac

message \
'     _    __  _    __  ____    ____    ____    __  _  __     ____        _____
    / /  / / / |  / / / __ \  / _  \  / _  \  / / | |/ /    / __ \      / ___/
   / /__/ / /  | / / / / / / / /_/ / / /_/ / / /  \   /    / /_/ /     / /_
  / / _ -  / /||/ / / / / / / ____/ / ____/ / /   /  |     \ _  \     / __ \
 / /  \ \ / / |  / / /_/ / / /     / /     / /   / /\ \   / /_/ / _  / /_/ /
/_/   |_|/_/  |_/  \____/ /_/     /_/     /_/   /_/ |_|   \____/ /_/ \____/'
message "${WELCOME} ... /w rambak"

if [ -n "$SPLASH" ] && [ -r /splash.ppm ] && type -p fbi >/dev/null 2>&1; then
 ( fbi -T 6 -1 -noedit -noverbose -t 45 /splash.ppm >/dev/null 2>&1 & )
fi

load_modules

# Terminalserver Section start
# check whether we are a terminal server client
TSCLIENT=""
checkbootparam "nfsdir" && TSCLIENT="yes"

# Check for "secure" option
SECURE=""
checkbootparam "secure" &&  SECURE="yes"

if [ -n "$TSCLIENT" ]; then
 # Split cmdline, find NFSDIR variable
 for i in $CMDLINE; do case "$i" in [Ii][Pp]=*|[Nn][Mm]=*|[Gg][Ww]=*|[Nn][Ff][Ss][Dd][Ii][Rr]=*) eval $i;; esac; done
 [ -n "$ip" ] && IP="$ip"
 [ -n "$nm" ] && NM="$nm"
 [ -n "$gw" ] && GW="$gw"
 [ -n "$nfsdir" ] && NFSDIR="$nfsdir"

 message ""
 sleep 5

 # Load nfs modules
 NFSMODULES="$(cd /modules/net; echo af_packet.*o sunrpc.*o lockd.*o nfs_acl.*o nfs.*o)"
 for i in $NFSMODULES; do
   insmod /modules/net/"$i" >/dev/null 2>&1
 done

 FOUND_NETWORK=""
 message "Loading network device module(s)"
 for i in $(cd /modules/net; echo *.*o); do
  case "$NFSMODULES" in
   *$i*) continue ;;
      *)
         case "$i" in
           00*) ;;
             *) message -n "${CRE} ${BLUE}Probing network device(s) handled by ${MAGENTA}$i${BLUE}.${NORMAL}"
                FOUND_NETWORK="$i" ;;
         esac
         insmod /modules/net/"$i" >/dev/null 2>&1 ;;
  esac
 done

 # Enable kernel messages again
 echo "6" > /proc/sys/kernel/printk
 ifconfig lo 127.0.0.1 up

 [ -n "FOUND_NETWORK" ] || debugshell

 if [ -n "$hostname" ]; then # hostname= bootparm
  HOSTNAME="$hostname"
  case "$HOSTNAME" in
   auto-clock) HOSTNAME="Knoppix-$(date +%F-%R | sed s/://g | sed s/-//g)";;
   auto-mac)   HOSTNAME="Knoppix-$(ifconfig eth0 | grep HWaddr | awk '{print $5}' | sed s/://g)";;
  esac
  message " ${BLUE}Hostname is ${MAGENTA}${HOSTNAME}${NORMAL}"
 fi

 DHCP=""
 # How many network cards should we probe for?
 for i in 0 1 2 3; do
  ifconfig "eth$i" up >/dev/null 2>&1 || continue
  message "${CRE}${BLUE}DHCP Broadcasting for IP address (${MAGENTA}eth$i${BLUE})... ${NORMAL}"
  if [ -n "$HOSTNAME" ]; then
   udhcpc -i eth$i -H $HOSTNAME && DHCP="eth$i"
  else
   udhcpc -i eth$i && DHCP="eth$i"
  fi
  [ -n "$DHCP" ] && break
  message "${RED}No answer from network.${NORMAL}"
 done
 [ -n "$DHCP" ] && message "${GREEN}OK.${NORMAL}" || debugshell

 message "${CRE} ${GREEN}Network card configuration: ${NORMAL}"
 ifconfig "$DHCP"

 # for the upcoming NFS mount
 MOUNTED=""
 SECUREOPTIONS=""
 [ -n "$SECURE" ] && SECUREOPTIONS=",nosuid"

 touch /etc/fstab

 # if we have an NFSDIR, try mounting it
 if [ -n "$NFSDIR" ]; then
# DEBUG:  message "nfsdir non-empty"
case $NFSDIR in //*) message "samba mount ==> skip nfs mount"; ;; *) #@@@GvR
  message -n "${CRE}${BLUE}Trying to mount CD on" \
          "${MAGENTA}$NFSDIR${BLUE}...${NORMAL}"
#@@@GvR message mount "${NFSDIR}" /mnt-system -o \
#@@@GvR       ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS 
  mount "${NFSDIR}" /mnt-system -o \
        ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS \
         > /dev/null 2>&1  && MOUNTED="yes"
#@@@GvR
  if [ "_$MOUNTED" != "_yes" ]; then
    message mount "${NFSDIR}" /mnt-system -o \
          ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS 
  fi
  KNXDIR="${NFSDIR%%:*}:/mnt-system"
  if [ "_$MOUNTED" == "_yes" ]; then
    if [ ! -h /mnt-system/$knoppix_dir/KNOPPIX ]; then message -n "${CRE}${MAGENTA}$NFSDIR/$knoppix_dir/KNOPPIX ${RED}does not exist${NORMAL} "
    else
      message -n "${CRE}${BLUE}Trying to nfs mount Knoppix on ${MAGENTA}$KNXDIR${BLUE}...${NORMAL}"
#     message mount "${KNXDIR}" /nfs-system -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS
              mount "${KNXDIR}" /nfs-system -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS > /dev/null 2>&1
    fi
  fi
;; esac
	# Try using other (SMB) mounts
	[ -z "$MOUNTED" ] && { if [ -n "$NFSDIR" ]; then
	    message -n "${CRE}${BLUE}Trying to SMB mount Knoppix on ${MAGENTA}$NFSDIR${BLUE}...${NORMAL}"
	    mount -t cifs "${NFSDIR}" /mnt-system -r -n -o user=guest,noserverino,nounix >/dev/null 2>&1  && MOUNTED="yes"
	    [ -z "$MOUNTED" ] && umount /mnt-system > /dev/null 2>&1
	fi; }
#@@GvR
        # unsuccessful? Blank out NFSDIR and see if pump does better
        [ -z "$MOUNTED" ] && message "${RED}Failed.${NORMAL}" && NFSDIR=
 fi

#@@@GvR message "this should have succeeded"
# message -n "this should have succeeded "

 # STILL nothing? ask the user
 [ -z "$MOUNTED" ] && {
    for i in 2 1 0; do
        message "${RED}Failed.${NORMAL}"
        message -n "${CYAN}Please enter NFS directory path" \
            "(aka \"192.168.0.1:/mnt-system\"): ${NORMAL}"
        read NFSDIR
        mount "$NFSDIR" /mnt-system \
        -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS \
        > /dev/null 2>&1  && MOUNTED="true"
        [ -n "$MOUNTED" ] && break
    done
 }

 [ -n "$MOUNTED" ] && message "${GREEN}OK.${NORMAL}"
 [ -z "$MOUNTED" ] && debugshell
 if test -r /mnt-system/$KNOPPIX_DIR/$KNOPPIX_NAME; then
  message -n "${CRE} ${GREEN}Accessing KNOPPIX NFS directory at ${MAGENTA}$NFSDIR${GREEN}...${NORMAL}"
  FOUND_KNOPPIX="true"
 else
  checkbootparam "bootfrom" || debugshell
 fi

fi
# TS Section end

# Return existing device names listed as regular expressions
listpartitions(){
 local pattern file
 for pattern in "$@"; do
  for file in $(find /sys/class/block -maxdepth 2 -name "$pattern"); do
   read size < "${file}"/size
   [ "$size" -lt 64 ] 2>/dev/null && continue
   file="${file##*/}"
   [ -b "/dev/$file" ] && echo "/dev/$file"
  done
 done
# awk 'BEGIN{old="__start"}/'"$1"'/{if($0==old){exit}else{old=$0;if($4&&$4!="name"){print "/dev/"$4}}}' /proc/partitions # Insufficient, does not find CD-Roms
}

#@@@GvR Bootfrom Section start
BOOTSYS="/mnt-system"   
if [ ! -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then
 # find BOOTFROM variable (/dev/sda1/boot/k620/*.iso)
 BOOTFROM=""; bootfrom="";
 for i in $CMDLINE; do case "$i" in [Bb][Oo][Oo][Tt][Ff][Rr][Oo][Mm]=*) eval $i;; esac; done
 [ -n "$bootfrom" ] && BOOTFROM="$bootfrom"
 if [ -n "$BOOTFROM" ]; then
  # we may have an ISO file, try mounting it
  BOOTISO="/mnt-iso"; BOOTDEV=""; BOOTFILE=""
  mkdir -p $BOOTISO $BOOTSYS
  [ -b /dev/loop1 ] || mknod -m 755 /dev/loop1 b 7 1
  if [ -n "$NFSDIR" ]; then
   umount $BOOTSYS; MOUNTED=""
#@@@GvR   message nfs remount "${NFSDIR}" "${BOOTISO}" -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS 
   case $NFSDIR in //*) message "samba mount ==> skip nfs mount"; ;; *)
    mount "${NFSDIR}" "${BOOTISO}" -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS > /dev/null 2>&1 && MOUNTED="yes" ;;
   esac
   if [ -z "$MOUNTED" ]; then
    message failed nfs mount "${NFSDIR}" "${BOOTISO}" -o ro,rsize=8192,wsize=8192,hard,nolock,intr$SECUREOPTIONS
    umount $BOOTISO >/dev/null 2>&1
    mount -t cifs "${NFSDIR}" "${BOOTISO}" -r -n -o user=guest,noserverino,nounix >/dev/null 2>&1 && MOUNTED="yes"
#@@@GvR     [ -z "$MOUNTED" ] && umount $BOOTISO > /dev/null 2>&1
    if [ -z "$MOUNTED" ]; then
     message failed cifs mount "${NFSDIR}" "${BOOTISO}" -r -n -o guest,noserverino,nounix
     umount $BOOTISO > /dev/null 2>&1
    fi
   fi
   BOOTFILE=$BOOTFROM
  else
   BOOTDEV=$(echo "$BOOTFROM" | awk -F/ '{print $1"/"$2"/"$3}')
   BOOTFILE="${BOOTFROM#*/}"; BOOTFILE="${BOOTFILE#*/}"; BOOTFILE="${BOOTFILE#*/}"
   message -n "${CRE}${BLUE}Trying to mount the ISO partition ${MAGENTA}$BOOTDEV${BLUE}...${NORMAL}"
   trymount "$BOOTDEV" "$BOOTISO" >/dev/null 2>&1
  fi
#@@@GvR  if [ ! -r "$BOOTISO/$BOOTFILE" ]; then umount $BOOTISO >/dev/null 2>&1
#@@@GvR   message "${CRE}${RED}Cannot mount the partition ${MAGENTA}$BOOTDEV${NORMAL} (cannot find: ${RED}${BOOTISO}/${BOOTFILE}${NORMAL})"
#@@@GvR   ls -al "$BOOTISO"
  ISOFILE=""
  [ -z "$ISOFILE" ] && [ -r "$BOOTISO/$BOOTFILE" ] && ISOFILE=$(ls -1 "$BOOTISO/$BOOTFILE" 2>/dev/null)
  [ -z "$ISOFILE" ] && [ -r  $BOOTISO/$BOOTFILE  ] && ISOFILE=$(ls -1  $BOOTISO/$BOOTFILE  2>/dev/null)
  FIRSTFILE=$(ls -1 $BOOTISO/$BOOTFILE 2>/dev/null | head -n1)
  if [ -z "$ISOFILE" ] && [ -n "$FIRSTFILE" ] && [ -r "$FIRSTFILE" ]; then ISOFILE="$FIRSTFILE"
   message -n "${RED}More than one ISO file !${YELLOW}"; ls -1 $BOOTISO/$BOOTFILE 2>/dev/null
   message    "${NORMAL}Try to use: ${MAGENTA}@${ISOFILE}#${NORMAL}"
  fi
  if [ -n "$ISOFILE" ] && [ ! -r "$ISOFILE" ]; then
   message "${CRE}${RED}Cannot mount the partition ${MAGENTA}$BOOTDEV${NORMAL} (cannot find: ${RED}${ISOFILE}${NORMAL})"
   ls -al "$BOOTISO"; umount $BOOTISO >/dev/null 2>&1
  else
#@@@GvR   message -n "${CRE}${BLUE}Trying to mount CD image on ${MAGENTA}${BOOTFILE}${BLUE}...${NORMAL}"
#@@@GvR   losetup /dev/loop1 "$BOOTISO/$BOOTFILE" && mount -r /dev/loop1 $BOOTSYS >/dev/null 2>&1
#@@@GvR   if [ ! -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then umount $BOOTSYS >/dev/null 2>&1
#@@@GvR    message -n "${CRE}${RED}Cannot mount CD image on ${MAGENTA}${BOOTFILE}${NORMAL}"
   message -n "${CRE}${BLUE}Trying to mount ISO image on ${MAGENTA}${ISOFILE}${BLUE} (${NORMAL}from: ${MAGENTA}${BOOTDEV}${NORMAL}) ...${NORMAL}"
   losetup /dev/loop1 $ISOFILE 2>/dev/null && mount -r /dev/loop1 $BOOTSYS >/dev/null 2>&1
   if [ ! -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then
    message  "${CRE}${RED}Cannot find $knoppix_dir dir in ISO image ${MAGENTA}${BOOTDEV}${YELLOW}/${BOOTFILE}${NORMAL} "
    umount "$BOOTSYS" >/dev/null 2>&1
    losetup -d /dev/loop1 >/dev/null 2>&1
   else
#@@@GvR    message -e "\r${CRE}${GREEN}$DISTRO ${FOUNDAT}: ${MAGENTA}${BOOTDEV}/$(cd $BOOTISO; ls -a $BOOTFILE)${NORMAL}       "
    message -e "\r${CRE}${GREEN}$DISTRO ${FOUNDAT}: ${MAGENTA}${BOOTDEV}${YELLOW}${ISOFILE}${NORMAL}       "
   fi
  fi
  # try to find ISO in an alternate location using the same path
  if [ ! -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then
   message -n "${CRE}${MAGENTA}Trying to find the ISO image in an other partition...${NORMAL}"
   # If USB storage device, wait for USB...
   if [ -d /sys/bus/usb/drivers/usb-storage ]; then WUSB="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; else WUSB="1"; fi
   for i in $WUSB ; do
    for BOOTDEV in $(listpartitions 'sd[a-z][0-9]*' 'sd[a-z]' 'mmcblk[0-9]p*' 'mmcblk[0-9]' 'hd[a-z][0-9]*' 'hd[a-z]' 'sr[0-9]*' 'scd[0-9]*'); do
     if [ -b "$BOOTDEV" ]; then
      message -n -e "\r${CRE}${BLUE}Searching for ISO in: ${MAGENTA}${BOOTDEV}${NORMAL}   "
      trymount "$BOOTDEV" "$BOOTISO" > /dev/null 2>&1
#@@@GvR      if [ ! -r "$BOOTISO/$BOOTFILE" ]; then umount $BOOTISO >/dev/null 2>&1; else
#@@@GvR       message -n "${CRE}${BLUE}Trying to mount CD image on ${MAGENTA}${BOOTFILE}${BLUE}...${NORMAL}"
#@@@GvR       losetup /dev/loop1 "$BOOTISO/$BOOTFILE" && mount -r /dev/loop1 $BOOTSYS >/dev/null 2>&1
      ISOFILE=""
      [ -z "$ISOFILE" ] && [ -r "$BOOTISO/$BOOTFILE" ] && ISOFILE=$(ls -1 "$BOOTISO/$BOOTFILE" 2>/dev/null)
      [ -z "$ISOFILE" ] && [ -r  $BOOTISO/$BOOTFILE  ] && ISOFILE=$(ls -1  $BOOTISO/$BOOTFILE  2>/dev/null)
      FIRSTFILE=$(ls -1 $BOOTISO/$BOOTFILE 2>/dev/null | head -n1)
      if [ -z "$ISOFILE" ] && [ -n "$FIRSTFILE" ] && [ -r "$FIRSTFILE" ]; then ISOFILE="$FIRSTFILE"
       message -n "${RED}More than one ISO file !${YELLOW}"; ls -1 $BOOTISO/$BOOTFILE 2>/dev/null
       message    "${NORMAL}Try to use: ${MAGENTA}${ISOFILE}${NORMAL}"
      fi
      if [ -n "$ISOFILE" ] && [ ! -r "$ISOFILE" ]; then
       umount $BOOTISO >/dev/null 2>&1
      else
       message -n "${CRE}${BLUE}Trying to mount ISO image on ${MAGENTA}${ISOFILE}${BLUE} (${NORMAL}from: ${MAGENTA}${BOOTDEV}${NORMAL}) ...${NORMAL}"
       losetup /dev/loop1 $ISOFILE 2>/dev/null && mount -r /dev/loop1 $BOOTSYS >/dev/null 2>&1
       if [ ! -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then
        umount $BOOTSYS >/dev/null 2>&1
        losetup -d /dev/loop1 >/dev/null 2>&1
        umount $BOOTISO >/dev/null 2>&1 ; #@@@GvR
       else
#@@@GvR        message -e "\r${CRE}${GREEN}$DISTRO ${FOUNDAT}: ${MAGENTA}${BOOTDEV}/$(cd $BOOTISO; ls -a $BOOTFILE)${NORMAL}       "
        message -e "\r${CRE}${GREEN}$DISTRO ${FOUNDAT}: ${MAGENTA}${BOOTDEV}${YELLOW}${ISOFILE}${NORMAL}       "
        break
       fi
      fi
     fi
    done
    if [ -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then
     break
    else
     message -n -e "\r${CRE}${BLUE}${WAITFORUSB}${NORMAL} $i ";
     sleep 1
    fi
   done
  fi
 fi
fi
if [ -r "$BOOTSYS/$knoppix_dir/KNOPPIX" ]; then MOUNTED="yes"; FOUND_KNOPPIX="true"; fi
#@@@GvR Bootfrom Section end


TOTALMEM=0
amount=$(awk -F: '/^MemTotal/{printf "%d",int($2); exit 0}' /proc/meminfo 2>/dev/null); #'
test "$amount" -gt "0" >/dev/null 2>&1 && let TOTALMEM=$amount/1024
read a b KERNEL relax >/dev/null 2>&1 </proc/version

# Print kernel info
message "${GREEN}Linux Kernel ${YELLOW}$KERNEL${GREEN}, ${MAGENTA}$TOTALMEM${GREEN} MB RAM.${NORMAL}"
# Print CPU info
message -n "${GREEN}"
[ -n "$SPLASH" ] || awk -F: '/^processor/{printf "CPU"$2": \t"};/^model name/{printf $2};/^vendor_id/{printf vendor};/^cpu MHz/{printf " @ %dMHz",int($2)};/^cache size/{printf ","$2" Cache"};/^$/{print ""}' /proc/cpuinfo 2>/dev/null | sed 's| \+| |g'
message -n "${NORMAL}"

# Avoid using the persistent image partition when booted via QEMU,
# unless "image" option present
NOIMAGE=""
SETRO=""
if grep -q -E '([Qq][Ee][Mm][Uu]|[Kk][Vv][Mm])' /proc/cpuinfo; then
 if ! checkbootparam image && ! checkbootparam useimage; then
   NOIMAGE="true"
   SETRO="true"
   RW="ro"
 fi
fi
if checkbootparam "noimage"; then
 NOIMAGE="true"
fi

#@@@GvR add "ramdisk" parameter to allow specifying ramdisk size, otherwise just use max(ram*4/5,2000)M
for i in $CMDLINE; do case "$i" in [Rr][Aa][Mm][Dd][Ii][Ss][Kk]=*) eval $i;; esac; done
case "$ramdisk" in
 [0-9]*[KMG]) RAMDISK="$ramdisk" ;;
esac
if [ -z "$RAMDISK" ]; then
 if [ "$TOTALMEM" -ge 2000 ] >/dev/null 2>&1; then
   RAMDISK="$(expr $TOTALMEM / 5)"; RAMDISK="$(expr $RAMDISK \* 4)M"
 else
   # Too large, but we can still use swapspace
   RAMDISK="2G"
 fi
fi
#@@@GvR

if [ -z "$FOUND_KNOPPIX" -a -z "$TSCLIENT" ]; then
 if [ -n "$root" ]; then
  if ! findknoppix $root; then
   if [ -d /sys/bus/usb/drivers/usb-storage ]; then
    for i in 1 2 3 4 5 6 7 8 9 10; do
     message -n -e "\r${CRE}${BLUE}${WAITFORUSB}${NORMAL}"
     sleep 2
     [ "$i" = 10 ] && export lastround=1
     findknoppix $root && break
    done
    [ "$?" = "0" ] || debugshell "${CRE}${RED}${NOTFOUND}${NORMAL}"
   else
    debugshell "${CRE}${RED}${NOTFOUND}${NORMAL}"
   fi
  fi
 elif ! findknoppix $(listpartitions 'sd[a-z][0-9]*' 'sd[a-z]' 'mmcblk[0-9]p*' 'mmcblk[0-9]' 'hd[a-z][0-9]*' 'hd[a-z]' 'sr[0-9]*' 'scd[0-9]*'); then
  if [ -d /sys/bus/usb/drivers/usb-storage ]; then
   for i in 1 2 3 4 5 6 7 8 9 10; do
    message -n -e "\r${CRE}${BLUE}${WAITFORUSB}${NORMAL}"
    sleep 2
    [ "$i" = 10 ] && export lastround=1
    findknoppix $root $(listpartitions 'sd[a-z][0-9]*' 'sd[a-z]' 'mmcblk[0-9]p*' 'mmcblk[0-9]' 'sr[0-9]*' 'scd[0-9]*') && break
   done
   [ "$?" = "0" ] || debugshell "${CRE}${RED}${NOTFOUND}${NORMAL}"
  fi
 fi
fi

checkbootparam "debug" && debugshell "Past mounting /mnt-system."

if checkbootparam "testcd" || checkbootparam "testdvd"; then
 if check_sha1sums; then
  message "${CRE}${GREEN}${ALLOK}${NORMAL}"; sleep 2
 else
  read -p "$CONTINUE" answer
  case "$answer" in
   [YyJjSs]*) true;;
   *) ask_reboot ;;
  esac
 fi
fi

# mount additional ramdisk for overlay
mount -t tmpfs -o size="$RAMDISK",mode=0755,dev,suid,exec tmpfs /ramdisk

# Check if we need to copy KNOPPIX-directory to ram or hd,
# contents will be available at /mnt-system later, in any case.
if checkbootparam toram; then
 copyto tmpfs
elif checkbootparam tohd; then
 copyto "$tohd"
else
 printlive; message ""
fi

# Run command from /KNOPPIX directory
runknoppixchroot(){
 local cmd="$1"; shift
 chroot /KNOPPIX "$cmd" "$@"
 return "$?"
}

runknoppixlib(){
 local cmd="$1"; shift
 [ -r /KNOPPIX/lib/ld-linux.so.2 -a -x /KNOPPIX/"$cmd" ] && /KNOPPIX/lib/ld-linux.so.2 --library-path "/KNOPPIX/lib:/KNOPPIX/lib/i386-linux-gnu:/KNOPPIX/usr/lib:/KNOPPIX/usr/lib/i386-linux-gnu" /KNOPPIX/"$cmd" "$@"
 return "$?"
}

# Createfile name size
createfile(){
 local src=/dev/zero rc=0
 echo -n "${CLEAR}${CREATING}"
 touch /tmp/progress.run
 while [ -r /tmp/progress.run ]; do
  echo -n "."
  sleep 2
 done &
 case "$1" in *.aes) src=/dev/urandom; esac
 # I thought that creating a sparse file would be quicker than writing
 # all data completely, but unfortunately, it has bad side effects if
 # the underlying FAT file system is fragmented. -KK
 #  dd if="$src" of="$1" bs=1M seek="$(($2 - 1))" count=1
 dd if="$src" of="$1" bs=1M count="$2"
 rc="$?"
 rm -f /tmp/progress.run; wait
 echo ""
 return "$rc"
}

createdata(){
 local rc size avail
 avail="$(df -m /mnt-system | awk '{size=$4}END{print size - 1}')"
 [ "$avail" -ge 200 ] 2>/dev/null || return 2
 runknoppixchroot /usr/bin/dialog --timeout 10 --inputbox "\n${CREATEIMG1}${avail}${CREATEIMG2}\n" 16 75 2>/tmp/knoppix.size; rc="$?"
 echo -n "${CLEAR}"
 read size </tmp/knoppix.size; rm -f /tmp/knoppix.size
 [ "$rc" = "0" -a "$size" -ge 200  -a "$size" -le "$avail" ] 2>/dev/null || return 3
 runknoppixchroot /usr/bin/dialog --yes-label "${ENCRYPT}" --no-label "${NO_ENCRYPT}" --defaultno --yesno "${QUESTION_ENCRYPT}" 16 75 2>/dev/null; rc="$?"
 echo -n "${CLEAR}"
 [ -b /dev/loop0 ]    || mknod -m 755 /dev/loop0 b 7 0
 [ -d /KNOPPIX-DATA ] || mkdir -m 755 /KNOPPIX-DATA
 if [ "$rc" = 0 ]; then # Encrypted
  local pw1="" pw2="" len=0 mods="" m
  setkeyboard
  while [ -z "$pw1" -o -z "$pw2" -o x"$pw1" != x"$pw2" -o "$len" -lt 4 ]; do
   [ -n "$pw1" ] && runknoppixchroot /usr/bin/dialog --msgbox "\n${PASSWORDS_NOMATCH}\n" 16 75 2>/dev/null
   runknoppixchroot /usr/bin/dialog --timeout 30 --insecure --passwordbox "\n${QUESTION_PASSWORD1}\n" 16 75 2>/tmp/knoppix.pw; rc="$?"
   read pw1 </tmp/knoppix.pw; rm -f /tmp/knoppix.pw
   [ "$rc" = 0 ] || return 4
   runknoppixchroot /usr/bin/dialog --insecure --passwordbox "\n${QUESTION_PASSWORD2}\n" 16 75 2>/tmp/knoppix.pw; rc="$?"
   read pw2 </tmp/knoppix.pw; len="$(wc -c /tmp/knoppix.pw | awk '{print $1}')"
   [ "$rc" = 0 ] || { rm -f /tmp/knoppix.pw; return 4; }
  done
  echo -n "${CLEAR}"
  for m in loop cryptoloop aes_generic aes_i586 cbc; do
   [ -d /sys/module/"$m" ] || mods="$mods $m"
  done
  [ -n "$mods" ] && runknoppixchroot /sbin/modprobe -a $mods >/dev/null 2>&1
  createfile /mnt-system/"$knoppix_dir"/knoppix-data.aes "$size"
  losetup -d /dev/loop0 2>/dev/null
  runknoppixlib /sbin/losetup -p 0 -e aes -k 256 /dev/loop0 /mnt-system/"$knoppix_dir"/knoppix-data.aes </tmp/knoppix.pw; rc="$?"; rm -f /tmp/knoppix.pw
  runknoppixlib /sbin/mke2fs -F -m 0 /dev/loop0
  sleep 2; echo -n "$CLEAR"
  mount -t ext2 -o rw /dev/loop0 /KNOPPIX-DATA && return 0
 else # Unencrypted
  createfile /mnt-system/"$knoppix_dir"/knoppix-data.img "$size"
  runknoppixlib /sbin/mke2fs -F -m 0 /mnt-system/"$knoppix_dir"/knoppix-data.img
  sleep 2; echo -n "$CLEAR"
  mount -t ext2 -o loop,rw /mnt-system/"$knoppix_dir"/knoppix-data.img /KNOPPIX-DATA && return 0
 fi
 return 1
}

# checkfs partition filesystem
checkfs(){
local p="$1" fs="${2:-ext2}"
message -n -e "\r${CRE}${YELLOW}$CHECKING ${CYAN}$p...${NORMAL} "
case "$fs" in
 ext*) runknoppixlib /sbin/e2fsck -y "$h" >/dev/null 2>&1 ;;
esac
message -n -e "\r${CRE}"
}

# mountaes partition mountpoint filesystem [options]
mountaes(){
 local p="$1" mp="${2:-/KNOPPIX-DATA}" fs="${3:-ext2}" mods="" m="" try="" h="" options="-o rw"
 [ -n "$4" ] && options="$4"
 for m in loop cryptoloop dm_crypt aes_generic aes_i586 cbc; do
  [ -d /sys/module/"$m" ] || mods="$mods $m"
 done
 [ -n "$mods" ] && runknoppixchroot /sbin/modprobe -a $mods >/dev/null 2>&1
 setkeyboard
 echo -n "${CYAN}$p "
 let try=1
 while [ "$try" -le 3 ]; do
  [ "$try" -gt 1 ] && echo -n "${CYAN}(#$try/3) "
  local h="" mapdev="${mp##*/}"
  if runknoppixlib /sbin/cryptsetup create --key-size 256 --cipher aes "$mapdev" "$p"; then # Use dm-crypt
   h=/dev/mapper/"$mapdev"
  elif runknoppixlib /sbin/losetup -e aes -k 256 /dev/loop0 "$p"; then
   h=/dev/loop0
  fi </dev/console
  echo -n "$NORMAL"
  if [ -b "$h" ]; then
   checkfs "$h"
   message -e "\r${CRE}${GREEN}${USING} ${YELLOW}$p${NORMAL}"
   mount -t "$fs" $options "$h" "$mp" && return 0
  fi
  losetup -d /dev/loop0 >/dev/null 2>&1
  runknoppixlib /sbin/cryptsetup remove "$mapdev" >/dev/null 2>&1
  let try++
 done
}

# check_data_partition
# echoes partition device on stdout if there is a /KNOPPIX-DATA set in knoppix-data.inf
# Return values: 0 - ok, 1 - not usable, 2 - not usable (silent), 3 - no partition configured, 100 - should be resized
check_data_partition(){
 local base
 local rootdisk="${ROOTDEV%[0-9]}"; rootdisk="${rootdisk%[0-9]}"
 case "$rootdisk" in /dev/mmcblk*) rootdisk="${rootdisk%p}";; esac
 for base in $home /mnt-system/"$knoppix_dir"/knoppix-data /mnt-system/knoppix; do
  [ -r "$base.inf" ] || continue
  local part="" mp="" fs="" opts=""
  while read part mp fs opts; do
   [ "$part" -gt "0" ] 2>/dev/null || continue
   case "$mp" in *[Hh][Oo][Mm][Ee]) mp="/KNOPPIX-DATA" ;; esac
   if [ "$mp" = "/KNOPPIX-DATA" ]; then
    local datapart=""
    case "$rootdisk" in
      /dev/sr*|/dev/scd*) return 2 ;;
      /dev/mmcblk*) datapart="${rootdisk}p${part}" ;;
      *) datapart="${rootdisk}${part}" ;;
    esac
    [ -b "$datapart" ] || return 2
    read_only "$datapart" && return 3 # ... 
    # If we reached this part, the data partition is valid.
    echo "$datapart"
    # Now check if we can resize.
    case "$opts" in *aes*) return 0;; esac # No resizable FS
    case "$fs" in
     reiserfs*)
      local label="$(dd if="${datapart}" skip=65636 bs=1 count=12 2>/dev/null)"
      if [ "$label" = "KNOPPIX-DATA" ]; then
       local sys_disk="/sys/block/${rootdisk##*/}"
       local sys_part="$sys_disk/${datapart##*/}"
       local disksize start size remaining
       read disksize < "$sys_disk/size"
       read start < "$sys_part/start"
       read size < "$sys_part/size"
       # All sizes are in 512-byte sectors, divide by 2 to get size in kB
       remaining="$(echo "$disksize" "$start" "$size" | awk '{print int(($1 - ($2 + $3)) / 2)}')"
       if [ "$remaining" -gt 8192 ] 2>/dev/null; then
#        echo "DEBUG: Partition ${rootdisk}${part} start $start size $size < disk size $disksize" >&2
        # Indicate resizability
        return 100
       fi
       return 0
      fi
      ;;
     *) return 0 ;; # Unsupported fs yet
    esac
   fi
  done < "$base.inf"
 done
 # No partition found - may retry with knoppix-data.img
 return 3
}

# resizedata partition_device
resizedata(){
 local rootdisk="${ROOTDEV%[0-9]}"; rootdisk="${rootdisk%[0-9]}"
 case "$rootdisk" in /dev/mmcblk*) rootdisk="${rootdisk%p}";; esac
 local partno="${1##*[a-zA-Z]}" # Only keep partition number
 local rc=0
 [ "$partno" -ge 1 ] 2>/dev/null || return 1
 [ -b "$rootdisk" ] || return 1
 # runknoppixlib /sbin/parted -s "$rootdisk" "resizepart $partno -1s" >/dev/null 2>&1
 echo ",+," | runknoppixlib /sbin/sfdisk --force --no-reread --quiet -N"$partno" "$rootdisk" >/dev/null 2>&1
 # Because /mnt-system is still mounted, rescanning partition table most certainly failed
 # Umount all and retry
 umountknoppix
 umountroot
 # Force rescan - doesn't work
 # [ -w /sys/block/"${rootdisk##*/}"/device/rescan ] && echo 1 > /sys/block/"${rootdisk##*/}"/device/rescan
 # Rewriting the MBR with fdisk does the trick
 echo w | fdisk -u "$rootdisk" >/dev/null 2>&1
 sleep 4
 # Remount all
 remountroot
 mountknoppix
# Now we should be able to resize data
 runknoppixlib /sbin/resize_reiserfs -fq "$1" >/dev/null 2>&1
 return "$?"
}

mountdata(){
 local img base ext m mods found="" rw="rw"
 local rootdisk="${ROOTDEV%[0-9]}"; rootdisk="${rootdisk%[0-9]}"
 case "$rootdisk" in /dev/mmcblk*) rootdisk="${rootdisk%p}";; esac
 ## read_only && rw="ro" ...
 ## for base in $home /mnt-system/"$knoppix_dir"/knoppix-data /mnt-system/knoppix; do ...
 for base in $home /ramdisk/knoppix-data /mnt-system/"$knoppix_dir"/knoppix-data /mnt-system/knoppix; do
  for ext in aes img inf; do
   img="$base.$ext"
   [ -r "$img" ]        || continue
   [ -b /dev/loop0 ]    || mknod -m 755 /dev/loop0 b 7 0
   [ -d /KNOPPIX-DATA ] || mkdir -m 755 /KNOPPIX-DATA
   [ -d /dev/mapper ]   || mkdir -m 755 /dev/mapper
   found="true"
   case "$ext" in
    aes)
     message -e "\r${CRE}${GREEN}${USING} ${YELLOW}$img ($rw,loop,crypt)${NORMAL}"
     mountaes "$img" /KNOPPIX-DATA ext2 "-o $rw" && found="true"
    ;;
    img)
     checkfs "$img" ext2
     # ...
     if [ "${img%/knoppix-data.img}" = '/ramdisk' ]; then rw="rw"; RW="rw"; fi
     message -e "\r${CRE}${GREEN}${USING} ${YELLOW}$img ($rw,loop)${NORMAL}"
     if mount -t ext2 -o loop,$rw "$img" /KNOPPIX-DATA; then
      found="true"
     else
      losetup -d /dev/loop0 >/dev/null 2>&1
     fi
    ;;
    inf) # Contains partition information in fstab format
     local part="" mp="" fs="" opts=""
     while read part mp fs opts; do
      case "$part" in \#*) continue;; esac
      part="${part#/dev/}"
      [ -n "$part" ] || continue
      case "$rootdisk" in /dev/mmcblk*)  part="p${part}";; esac
      case "$mp" in *[Hh][Oo][Mm][Ee]) mp="/KNOPPIX-DATA" ;; esac
      [ -z "$mp" ] || mp="/KNOPPIX-DATA"
      case "$opts" in
       *aes*) message -e "\r${CRE}${GREEN}${USING} ${YELLOW}${rootdisk}${part} ($rw,crypt)${NORMAL}"
              mountaes "${rootdisk}${part}" "${mp}" "${fs:-ext2}" "-o $rw" && [ "$mp" = "/KNOPPIX-DATA" ] && found="true" ;;
       *)     checkfs "${rootdisk}${part}" "$fs"
              message -e "\r${CRE}${GREEN}${USING} ${YELLOW}${rootdisk}${part} ($rw)${NORMAL}"
              mount -t "${fs:-ext2}" -o $rw "${rootdisk}${part}" "${mp}" && [ "$mp" = "/KNOPPIX-DATA" ] && found="true" ;;
      esac
     done <"$img"
    ;;
   esac
  done
 done
 if [ -z "$found" -a "$RW" = "rw" ]; then
  if checkbootparam "mkimage"; then
   createdata && return 0
  fi
 fi
 if [ -n "$found" ]; then
   if [ "$(getmpsize /KNOPPIX-DATA)" -ge 400 ]; then
    return 0
   else
    # Too small!
    message "${RED}Overlay /KNOPPIX-DATA: ${TOOSMALL}${NORMAL}"
    umount /KNOPPIX-DATA 2>/dev/null
   fi
 fi
 [ -d /KNOPPIX-DATA ] && rmdir /KNOPPIX-DATA
 return 1
}

# -----------
# findrambak devices...
RAMBAK=""
findrambak(){
 local dev RBAKFILE=''
 local rambakfile=knoppix-data.tar.gz
 local rambakdata=knoppix-data.img
 local rambakempty=knoppix-data.img.empty.tar.gz
 # local rambaksize=3372 # ~3.3GB # for note
 for d in sda sda1 sdb sdb1 sdc1 sdd1 sde1 sdf1; do
  dev=/dev/$d
  [ -b "$dev" ] || continue
  message -n -e "\r${CRE}${BLUE}trying rambak in: ${MAGENTA}$dev${NORMAL}"
  # make sure folder rambak exists in USB or BOOT disk/device
  mount $dev /mnt-system/rambak >/dev/null 2>&1 || continue
  sleep 1
  RBAKFILE=/mnt-system/rambak/KNOPPIX${KVERS}/${rambakfile}
  if [ -r "$RBAKFILE" ]; then
   RBAKFILE=$RBAKFILE
  else
   RBAKFILE=/mnt-system/rambak/${rambakfile}
  fi

  # --------------------------------------------------------------------
  # Use 'knoppix-data.img' directly from other media (not knoppix disk)
  # --------------------------------------------------------------------
  if checkbootparam "ramdisklink"; then
   message -n -e "\r${CRE}${BLUE}linking ${rambakdata} image from: ${MAGENTA}$dev${NORMAL}"
   RAMBAKDISK=/mnt-system/rambak/KNOPPIX${KVERS}/${rambakdata}
   cd /ramdisk; mkdir tmp
   if [ -r "$RAMBAKDISK" ]; then
    ln -s ${RAMBAKDISK} ./ >/dev/null 2>&1 || continue
    RAMBAK="$dev"; RW="rw"
    return 0
   fi
   message -n -e "\r${CRE}${RED}linking ${rambakdata} image from: ${MAGENTA}$dev${NORMAL} FAILED"
   umount /mnt-system/rambak >/dev/null 2>&1
   RAMBAK=""
   return 1
  fi
  # --------------------------------------------------------------------
  
  if [ -r "$RBAKFILE" ]; then
   message -n -e "\r${CRE}${GREEN}${rambakfile} ${FOUNDAT}: ${MAGENTA}$dev${NORMAL}       "
   cd /ramdisk; mkdir tmp
   cp $RBAKFILE /ramdisk/

   cp /mnt-system/rambak/${rambakempty} ./
   tar -zxf ${rambakempty} >/dev/null 2>&1
   mount -t ext2 -o loop,rw ${rambakdata} tmp >/dev/null 2>&1 || continue

   cd tmp; tar -zxf "/ramdisk/${rambakfile}" >/dev/null 2>&1
   cd /ramdisk; umount tmp >/dev/null 2>&1
   # rm -f "/ramdisk/${rambakfile}" "/ramdisk/${rambakempty}" #leave for trace
   RAMBAK="$dev"; RW="rw"
   return 0
  fi
  message -e "\r${CRE}${RED}NOT IN: ${MAGENTA}$dev${NORMAL}       "
  umount /mnt-system/rambak >/dev/null 2>&1
  RAMBAK=""
 done
 return 1
}

mountknoppix(){
 local k dev dir count=0 RC=0 k2 dev2 dir2 k3 dev3 dir3 # ...
 [ -b /dev/cloop ] || mknod -m 644 /dev/cloop b 240 0
 grep -q cloop /proc/devices     || insmod /mnt-system/"$knoppix_dir"/modules/cloop.ko preload=32 || return 2
 grep -q aufs  /proc/filesystems || insmod /mnt-system/"$knoppix_dir"/modules/aufs.ko || return 3
 modprobe loop
 grep -q squashfs  /proc/filesystems || insmod /mnt-system/"$knoppix_dir"/modules/squashfs.ko || return 3
 local bn bd bkname bnum k2dir k2dirmnt k3dir k3dirmnt
 # Note dummy file KNOPPIX<num> (cloop format) need to be present
 # in KNOPPIX/ or KNOPPIX${KVERS}/ for .sfs and .d directories to get activated.
 for k in /mnt-system/"$knoppix_dir"/[Kk][Nn][Oo][Pp][Pp][Ii][Xx] \
          /mnt-system/"$knoppix_dir"/[Kk][Nn][Oo][Pp][Pp][Ii][Xx][0-9] \
          /mnt-system/rambak/KNOPPIX${KVERS}/[Kk][Nn][Oo][Pp][Pp][Ii][Xx][0-9]; do
  bd=$(dirname $k)
  bn=$(basename $k)
  # bkname=$(echo $bn | cut -b -5)     # format [Kk][Nn][Oo][Pp][Pp][Ii][Xx]
  # bnum=${bn//[KkNnOoPpPpIiXx]/}      # format [0-9]
  k2dir=${bd}'.sf4'                    # format <dirname>.sf4
  k2=${k2dir}'/'${bn}'.sf4'            # format <dirname>.sf4/KNOPPIX<num>.sf4
  k3dir=${bd}'.d'                      # format <dirname>.d
  k3=${k3dir}'/'${bn}'.d'              # format <dirname>.d/KNOPPIX<num>.d

  [ -r "$k" ] || continue
  check_knoppix "$k"
  if [ $count = 0 ]; then
   dev=/dev/cloop; dir=/KNOPPIX
   dev2=/dev/loop; dir2='/KNOPPIX.sf4'
   dev3=$k3dir; dir3=/KNOPPIX.d  # for -bind mounting
  else
   dev=/dev/cloop$count; dir=/KNOPPIX$count
   [ -b $dev ] || mknod -m 644 $dev b 240 $count
   dev2=/dev/loop$count ; dir2='/KNOPPIX'"$count"'.sf4'
   # add /dev/loop devices
   # [ -b $dev2 ] || mknod -m 640 $dev2 b 7 $count # not needed
   dev3=$k3; dir3='/KNOPPIX'"$count"'.d'  # for -bind mounting

   [ -d $dir ] || mkdir -m 755 $dir
  fi
  if ! losetup $dev $k >/dev/null 2>&1 || ! mount -r -t iso9660 $dev $dir >/dev/null 2>&1; then
   # Verbose error message
   echo -n -e "\n\r${RED}${BROKENIMAGE}: $k ${ON} "; mount | grep /mnt-system; dmesg | tail | grep cloop; echo -n "${NORMAL}"
   # Clean up for next retry
   umountknoppix
   return 4
  fi
  if [ -r "$k2" ]; then
   echo -n -e "${GREEN} $(basename $k2) ${NORMAL}"
   [ -d $dir2 ] || mkdir -m 755 $dir2
#   if ! losetup $dev2 $k2 >/dev/null 2>&1 || ! mount -r -t squashfs $dev2 $dir2 >/dev/null 2>&1; then
   if ! mount -r -t squashfs $k2 $dir2 >/dev/null 2>&1; then
    echo "============= ERROR: $k2 ============="
    # Verbose error message
    echo -n -e "\n\r${RED}${BROKENIMAGE}: $k2 ${ON} "; mount | grep /mnt-system; dmesg | tail | grep ' loop'; echo -n "${NORMAL}"
    umountknoppixsfs
   fi
  fi
  if [ -r "$k3" ]; then
   echo -n -e "${YELLOW} $(basename $k3) ${NORMAL}"
   [ -d $dir3 ] || mkdir -m 755 $dir3
   # if ! mount -o bind,ro $k3 $dir3 >/dev/null 2>&1; then # mount(8) since v2.27
   if ! mount -r -o bind $k3 $dir3 >/dev/null 2>&1; then
    echo "============= ERROR: $k3 ============="
    # Verbose error message
    echo -n -e "\n\r${RED}${BROKENIMAGE}: $k3 ${ON} "; mount | grep /mnt-system; dmesg | tail | grep '.d'; echo -n "${NORMAL}"
    umountknoppixd
   fi
  fi

  let count++
 done
 return 0
}

# Release all Knoppix compressed/readonly file systems # ...
umountknoppix(){
 for dev in /dev/cloop*; do
  umount -f "$dev" >/dev/null 2>&1
  losetup -d "$dev" >/dev/null 2>&1
 done
}
umountknoppixsfs(){  # sf4 ...
 for dev in /dev/loop*; do
  umount -f "$dev" >/dev/null 2>&1
  losetup -d "$dev" >/dev/null 2>&1
 done
}
umountknoppixd(){  # .d dirs ...
 for dev in /KNOPPIX*.d; do
  umount -f "$dev" >/dev/null 2>&1
 done
}

# Release the /mnt-system root partition
umountroot(){
 umount -f /mnt-system
}

# Remount the /mnt-system root partition
remountroot(){
  [ -b "$ROOTDEV" ] || return 1
  trymount "$ROOTDEV" /mnt-system >/dev/null 2>&1 || return 1
}

mountunion(){
 local dir tree="" d2="" d3=""  # ...
 for dir in /KNOPPIX /KNOPPIX[0-9]; do
  d2=$dir'.sf4'; d3=$dir'.d'
  [ -d "$dir" ] && tree="$dir=ro${tree:+:$tree}"
  [ -d "$d2" ] && tree="$d2=ro${tree:+:$tree}" # ...
  [ -d "$d3" ] && tree="$d3=ro${tree:+:$tree}"
 done
 # echo "========== $tree =========="
 mount -t aufs -o "br:$1:$tree,noplink" unionfs /UNIONFS
 return $?
}

# -----------
message -n -e "${CRE}${RED}Trying to find rambak disk...${NORMAL}"
# -----------
if findrambak; then
  message -e "${CRE}${BLUE}knoppix-data.img found, rambak disk mounted...${NORMAL}"
  RW="rw"
else
  message -e "${CRE}${BLUE}Trying to rsync root.overlay on ${MAGENTA}/ramdisk${BLUE}...${NORMAL}"
  # tar -zxf /mnt-system/rambak/root.overlay.tar.gz -C / > /dev/null 2>&1 
fi
sleep 4
# -----------


if mountknoppix; then # compressed
 checkbootparam "debug" && debugshell "Past mounting /KNOPPIX."
 if test -z "$NOIMAGE" && test -z "$TSCLIENT"; then
  data_partition="$(check_data_partition)"
  dstat="$?"
  case "$dstat" in
   100) message -n -e "\r${CRE}${YELLOW}${EXPANDING} KNOPPIX-DATA Partition $data_partition... ${NORMAL}"
        if resizedata "$data_partition"; then
	  message "${GREEN}OK.${NORMAL}"
	else
          message "${RED}${FAILED}${NORMAL}"
	  dstat=1
	fi
	;;
     3) ;; 
     2) ;; 
     1) message "${CRE}${RED}KNOPPIX-DATA Partition $data_partition exists, but cannot be used.${NORMAL}" ;; 
     0) message "${CRE}${GREEN}KNOPPIX-DATA Partition $data_partition OK${NORMAL}";;
  esac
  message -e "\r${CRE}${RED}1.dstat -> $dstat${NORMAL}"
  if [ "$dstat" != 1 -a "$dstat" != 2 ] && mountdata; then
   checkbootparam "debug" && debugshell "Past mounting /KNOPPIX-DATA."
   # if [ "$RW" = "ro" ] || read_only "$ROOTDEV"; then # ...
   if [ "$RW" = "ro" ]; then
    message -n -e "\r${CRE}${RED}Still RO...${NORMAL}"
    mountunion /ramdisk=rw:/KNOPPIX-DATA=ro
   else
    message -n -e "\r${CRE}${BLUE}Final attempt to get RW right. ...${NORMAL}"
    mountunion /KNOPPIX-DATA=rw
   fi
  else
   mountunion /ramdisk=rw
  fi
 else
  message -e "\r${CRE}${RED}2.dstat -> $dstat${NORMAL}"
  mountunion /ramdisk=rw
  if [ -n "$SETRO" ]; then
   # Set all partitions on root disk to read-only
   case "$ROOTDEV" in
    /dev/sr*|/dev/scd*) rootdisk="$ROOTDEV";;
    *) rootdisk="${ROOTDEV%[0-9]}"; rootdisk="${rootdisk%[0-9]}" ;;
   esac
   case "$rootdisk" in /dev/mmcblk*) rootdisk="${rootdisk%p}";; esac
   runknoppixlib /sbin/blockdev --setro "$rootdisk"
   for i in 1 2 3 4 5 6 7 8 9 12 11 12 13 14 15 16; do
    [ -b "$rootdisk$i" ] && runknoppixlib /sbin/blockdev --setro "$rootdisk$i" >/dev/null 2>&1
   done
  fi
 fi
else
 debugshell "${RED}${NOKNOPPIX}${NORMAL}"
fi

checkbootparam "debug" && debugshell "Past mounting /UNIONFS."

[ -n "$HOSTNAME" ] && echo "$HOSTNAME" > /UNIONFS/etc/hostname
grep -q ^nameserver /etc/resolv.conf 2>/dev/null && cat /etc/resolv.conf > /UNIONFS/etc/resolv.conf

# Link directories in order to create a writable system
PATH="$PATH:/bin.old:/UNIONFS/bin:/UNIONFS/sbin"
export PATH

# Create symlinks to /UNIONFS
for i in boot etc sbin var lib lib64 libx32 opt root bin; do
 if test -d /$i; then
  mv /$i /$i.old && \
   ln -s /UNIONFS/$i /$i && \
   rm -rf /$i.old
 elif [ -d /UNIONFS/$i ]; then
  ln -snf /UNIONFS/$i /$i
 fi
done

# Unfortunately, virtualbox fails to work with symlinks in
# the library paths, so we switch /usr to bind mounts for now.
# /home should ALWAYS be a mountpoint, not a link (or you get an ugly prompt)
for i in usr home; do # Move directories to union
 if [ -d /UNIONFS/$i ]; then
  test -L /$i && rm -f /$i
  test -d /$i || mkdir -m 755 /$i
  mount -o bind /UNIONFS/$i /$i
 fi
done

# Try to reduce CD/DVD latency by increasing read-ahead buffer
# and forcing the low-latency bfq scheduler
case "$ROOTDEV" in
 /dev/sr*)
  rafile=/sys/block/"${ROOTDEV#/dev/}"/queue/read_ahead_kb
  schedfile=/sys/block/"${ROOTDEV#/dev/}"/queue/scheduler
  [ -f "$rafile" ] && echo 2048 > "$rafile" 2>/dev/null
  [ -f "$schedfile" ] && echo bfq > "$schedfile" 2>/dev/null
 ;;
esac

checkbootparam "debug" && debugshell "Past symlinks to /UNIONFS."

# Check for updates on-disk, install them if necessary. Add rambak ... 
# ls /mnt-system/KNOPPIX/update*.zip /mnt-system/KNOPPIX/update*.tar.gz /mnt-system/KNOPPIX/update*.taz 2>/dev/null | while read update; do
ls /mnt-system/rambak/KNOPPIX"$KVERS"/update*.tar.gz /mnt-system/KNOPPIX/update*.zip /mnt-system/KNOPPIX/update*.tar.gz /mnt-system/KNOPPIX/update*.taz 2>/dev/null | while read update; do
 if [ -r "$update" ]; then
  message -e "\r${CRE}${GREEN}${UPDATING} ${YELLOW}$update${NORMAL}"
  case "$update" in
   *.zip) ( cd / ; unzip -o "$update" >/dev/null 2>&1 ) ;;
   *.tar.gz|*.taz) ( cd / ; tar -zxf "$update" >/dev/null 2>&1 ) ;;
  esac
 fi
done

export RAMBAK=$RAMBAK

# Before starting init: check for "adriane" or "secure" bootoption
CONFS="/etc/inittab /etc/sudoers /etc/PolicyKit/PolicyKit.conf"
if checkbootparam "adriane" && type -p adriane >/dev/null 2>&1; then
 for i in $CONFS; do
  s="$i.adriane"; o="$i.orig"
  if [ -r "$s" ]; then
   [ -r "$o" ] || mv -f "$i" "$o" >/dev/null 2>&1
   cp -f "$s" "$i"
  fi
 done
elif checkbootparam "secure"; then
 for i in $CONFS; do
  s="$i.secure"; o="$i.orig"
  if [ -r "$s" ]; then
   [ -r "$o" ] || mv -f "$i" "$o" >/dev/null 2>&1
   cp -f "$s" "$i"
  fi
 done
else
 for i in $CONFS; do
  o="$i.orig"
  [ -r "$o" ] && mv -f "$o" "$i" >/dev/null 2>&1
 done
fi

export SELINUX_INIT=NO
# echo 0x0100 >/proc/sys/kernel/real-root-dev # unnecessary, since we never leave

# Run a shell in debug mode before starting init
checkbootparam "debug" && debugshell "Final DEBUG Shell before starting init."

# Create trace=open for mkisofs sortlist optimization
# We store the result in /open.trace because /tmp gets mounted over.
checkbootparam "trace" && strace -q -f -o /open.trace -e "trace=open" -p 1 &

for i in $CMDLINE; do case "$i" in init=*) eval $i;; esac; done

# Start init
if [ -n "$init" ]; then
 if [ ! -x "$init" ]; then
  if type -p "${init##*/}" >/dev/null 2>&1; then
   init="$(type -p "${init##*/}")"
  else
   message "${RED}$init $DOESNOTEXIST${NORMAL}"
   init="/sbin/init"
  fi
 fi
 message "${YELLOW}INIT=$init${NORMAL}"
 setkeyboard
fi

# Make sure we always have an init at the end!
[ -n "$init" -a -f "$init" -a -x "$init" ] || init="/sbin/init"

exec "$init" "$@" </dev/console >/dev/console 2>&1

message 

ask_reboot