summaryrefslogtreecommitdiff
path: root/utils/sb2
blob: f1a6dbe80cda0f598e76066a5af2334a0e1dba89 (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
#!/bin/bash
# Copyright (C) 2006,2007 Lauri Leukkunen <lle@rahina.org>
# Licensed under GPL version 2

function version()
{
	cat $SBOX_DIR/share/scratchbox2/version
}

function usage()
{
	cat <<EOF
sb2 - crosscompiling environment
Usage:
    sb2 [OPTION]... [COMMAND] [PARAMETERS]

If no COMMAND is given, a bash shell in scratchbox2 environment is started.

Options:
    -v           display version
    -L level     enable logging (levels=one of error,warning,notice,info,debug,noise,noise2,noise3)
    -d           debug mode: log all redirections (logging level=debug)
    -h           print this help
    -t TARGET    target to use, use sb2-config -d TARGET to set a default
    -e           emulation mode
    -m MODE      use mapping mode MODE
    -M file      read mapping rules from "file"
    -s DIRECTORY load mapping scripts from alternative location
    -Q BUGLIST   emulate bugs of the old scratchbox 1 (BUGLIST consists of
                 letters: 'x' enables exec permission checking bug emulation)
    -r           do not create reverse mapping rules
    -O options   set options for the selected mapping mode ("options" is
                 a mode-specific string)
    -R           use simulated root permissions (currently activates
                 "fakeroot" for this functionality)
    -S file      Write session information to "file" (see option -J)
    -J file      Don't create a new session; join an existing one (see -S) 
    -D file      delete an old session (see -S). Warning: this does not
                 check if the session is still in use!
    -W dir       Use "dir" as the session directory when creating the session
                 ("dir" must be absolute path and must not exist. N.B. long 
                 pathnames here may cause trouble with socket operations) 
    -c           When creating a session, also create a private copy
                 of target_root (rootstrap). Note that this can be
                 really slow, depending on the size of the orig.target_root
    -C dir       When creating a session, create copy of "dir" and use it as the 
                 target_root (rootstrap).
    -T dir       use "dir" as tools_root (overriding the value from config file)

Examples:
    sb2 ./configure
    sb2 make
    sb2 -e make install
    sb2 -m emulate make install
EOF
	exit 2
}

function exit_error()
{
	echo "sb2: Error: $@"
	exit 1
}

function sanity_check()
{
	if [ `id -u` = 0 ]; then
		exit_error "Do not use sbox2 as root!"
	fi
	# check that most important host and target files exist
}

# Collect & write mapping- and policy rules to $SBOX_SESSION_DIR/rules/*
#
# Parameters:
#  - output file name
#  - mapping mode name
#  - list of rule files (if specified by the -M option)
function write_rules_to_session_dir()
{
	output_file_name=$1
	mapmode_name=$2
	shift 2
	input_files="$@"

	cat >$output_file_name <<END
-- Rules for session $SBOX_SESSION_DIR
-- Automatically generated file, do not edit.
--
END
	
	for f in $input_files; do
		if [ -r $f ]; then
			echo "-- [ $f ]" >>$output_file_name
			cat $f >>$output_file_name
		else
			echo "-- [ Failed to read $f ]" >>$output_file_name
		fi
	done
}

# Create reverse rules. Since that will be done using sb2-show, the environment
# must to be ready => this function can be called only just before the shell
# is executed at end of this script.
function create_reverse_rules()
{
	for ammf in $SBOX_SESSION_DIR/rules/*.lua; do
		amm_base=`basename $ammf .lua`

		SBOX_SESSION_MODE=$amm_base sb2-monitor \
			-L $SBOX_LIBSB2 -- $SBOX_DIR/bin/sb2-show \
			execluafile \
			$SBOX_SESSION_DIR/lua_scripts/create_reverse_rules.lua \
			>$SBOX_SESSION_DIR/rev_rules/$amm_base.lua
	done
}

#
# Generates argvmods for cross-compilers and misc binaries.
# Generated files are placed under $SBOX_SESSION_DIR/argvmods/.
#
function create_argvmods_rules()
{
	/bin/mkdir -p $SBOX_SESSION_DIR/argvmods
	SBOX_ARGVMODS_SOURCE_FILE="argvenvp_misc.lua" sb2-monitor \
	    -L $SBOX_LIBSB2 -- $SBOX_DIR/bin/sb2-show \
	    execluafile \
	    $SBOX_SESSION_DIR/lua_scripts/create_argvmods_rules.lua \
	    >$SBOX_SESSION_DIR/argvmods/argvmods_misc.lua
	SBOX_ARGVMODS_SOURCE_FILE="argvenvp_gcc.lua" sb2-monitor \
	    -L $SBOX_LIBSB2 -- $SBOX_DIR/bin/sb2-show \
	    execluafile \
	    $SBOX_SESSION_DIR/lua_scripts/create_argvmods_rules.lua \
	    >$SBOX_SESSION_DIR/argvmods/argvmods_gcc.lua
}

# Create some additional rules for the default mapping mode:
function create_argvmods_usr_bin_rules()
{
	default_rule=$1

	for ammf in $SBOX_SESSION_DIR/rules/Default.lua \
		    $SBOX_SESSION_DIR/rules/$SBOX_MAPMODE.lua; do
		amm_base=`basename $ammf .lua`

		SBOX_ARGVMODS_USR_BIN_DEFAULT_RULE="$default_rule" \
		SBOX_SESSION_MODE=$amm_base sb2-monitor \
			-L $SBOX_LIBSB2 -- $SBOX_DIR/bin/sb2-show \
			execluafile \
			$SBOX_SESSION_DIR/lua_scripts/create_argvmods_usr_bin_rules.lua \
			>$SBOX_SESSION_DIR/rules/$amm_base.ARGVMODS
		# add the generated rules to the beginning of the rule file
		cat $SBOX_SESSION_DIR/rules/$amm_base.ARGVMODS $ammf \
		    >$SBOX_SESSION_DIR/rules/$amm_base.NEW
		mv $SBOX_SESSION_DIR/rules/$amm_base.NEW $ammf
		rm $SBOX_SESSION_DIR/rules/$amm_base.ARGVMODS
	done
}

function set_and_check_SBOX_TARGET()
{
	if [ -z "$SBOX_TARGET" ]; then
		if [ -r ~/.scratchbox2/config ]; then
			. ~/.scratchbox2/config
		fi
		SBOX_TARGET=$DEFAULT_TARGET
	fi

	if [ -z "$SBOX_TARGET" ]; then
		exit_error "No target specified and none set as default, aborting."
	fi

	if [ ! -e ~/.scratchbox2/$SBOX_TARGET/sb2.config ]; then
		exit_error "Invalid target specified, aborting."
	fi
}

function load_configuration()
{
	#-----------
	# part of the configuration is still stored in the "old format"
	# configuration file, "sb2.config". It is created by "sb2-init"

	. ~/.scratchbox2/$SBOX_TARGET/sb2.config
	# Remember where SBOX_TARGET_ROOT was in the configuration file
	SBOX_TARGET_ROOT_in_config_file=$SBOX_TARGET_ROOT

	#-----------
	# "New" config system stores configuration to various files
	# in sb2.config.d directory, and the configuration is automatically
	# upgraded whenever needed:
	
	# check if we need to upgrade configuration:
	if [ ! -f ~/.scratchbox2/$SBOX_TARGET/sb2.config.d/config-stamp.14 ]; then
		$SBOX_DIR/share/scratchbox2/scripts/sb2-upgrade-config \
			$SBOX_TARGET
		if [ $? != 0 ]; then
			echo "Failed to upgrade configuration files" >&2
			exit 1
		fi
	fi

	#-----------
	# Read in primary toolchain config, if it has been defined
	if [ -f $HOME/.scratchbox2/$TARGET/sb2.config.d/gcc.config.sh ]; then
		. $HOME/.scratchbox2/$TARGET/sb2.config.d/gcc.config.sh
	fi
}

function clone_target_root_dir_from()
{
	source_directory=$1

	echo "Copying target root from $source_directory..."
	# cp -Rp does not preserve hard links, but cpio does
	(cd $source_directory; find . -depth -print |
		cpio -pamd $SBOX_SESSION_DIR/target_root)
	#
	# We store path of the original target root here.  It
	# is used later on when libsb2 search path is being formed.
	#
	SBOX_CLONED_TARGET_ROOT=$source_directory
	SBOX_TARGET_ROOT=$SBOX_SESSION_DIR/target_root
	SB2_TEMP_DPKG_ADMIN_DIR=$SBOX_SESSION_DIR/tmp-pkg-db
	mkdir -p $SB2_TEMP_DPKG_ADMIN_DIR
}

function sboxify_environment()
{
	LD_LIBRARY_PATH=$SBOX_DIR/lib/libsb2:$SBOX_DIR/lib64/libsb2:$SBOX_DIR/lib32/libsb2:/emul/lib64/libsb2:/emul/lib32/libsb2
	SBOX_LIBSB2="libsb2.so.1"
	
	load_configuration

	# override SBOX_TOOLS_ROOT if requested by command-line option
	if [ -n "$SBOX_FORCED_TOOLS_ROOT" ]; then
		SBOX_TOOLS_ROOT=$SBOX_FORCED_TOOLS_ROOT
	fi

	# Check that tools exist (or at least the directory exists)
	if [ ! -d "$SBOX_TOOLS_ROOT" ]; then
		exit_error "Tools directory '$SBOX_TOOLS_ROOT' does not exist."
	fi

	if [ -d $SBOX_SESSION_DIR/target_root ]; then
		# A copy of target_root already exists, use that
		# (this may happen when we are joining an old
		# session, see options -J and -c)
		SBOX_TARGET_ROOT=$SBOX_SESSION_DIR/target_root
		SB2_TEMP_DPKG_ADMIN_DIR=$SBOX_SESSION_DIR/tmp-pkg-db
	elif [ "$OPT_CLONE_TARGET_ROOT" == "y" ]; then
		# SBOX_TARGET_ROOT has been set, make a clone of it
		clone_target_root_dir_from $SBOX_TARGET_ROOT
	elif [ -n "$OPT_CLONE_TARGET_ROOT_FROM" ]; then
		if [ -d "$OPT_CLONE_TARGET_ROOT_FROM" ]; then
			# the source is a directory, clone it.
			clone_target_root_dir_from $OPT_CLONE_TARGET_ROOT_FROM
		elif [ ! -e "$OPT_CLONE_TARGET_ROOT_FROM" ]; then
			exit_error "'$OPT_CLONE_TARGET_ROOT_FROM' does not exist."
		else
			exit_error "Don't know how to create target root from '$OPT_CLONE_TARGET_ROOT_FROM'"
		fi
	else
		SB2_TEMP_DPKG_ADMIN_DIR=$HOME/.scratchbox2/$SBOX_TARGET.tmp-pkg-db.$SBOX_MAPMODE
	fi

	# SBOX_MAPMODE has been set, read mode-specific settings
	if [ -f $SBOX_DIR/share/scratchbox2/modeconf/sb2rc.$SBOX_MAPMODE ]; then
		. $SBOX_DIR/share/scratchbox2/modeconf/sb2rc.$SBOX_MAPMODE starting
	fi

	if [ "$SBOX_CONFIG_VERSION" -lt "9" ]; then
		echo "Please run sb2-init for your target"
		echo "to update its sb2.config to work with current version of sb2."
		exit 1
	fi

	if [ -n "$SBOX_DIR" ]; then
		if [ -z "$SBOX_LUA_SCRIPTS" ]; then
			SBOX_LUA_SCRIPTS="$SBOX_DIR/share/scratchbox2/lua_scripts"
		fi
	else
		exit_error "Incorrect target config in ~/.scratchbox2/$SBOX_TARGET/sb2.config"
	fi

	# This refers to the primary toolchain.
	# FIXME: $SBOX_TARGET_TOOLCHAIN_DIR should be removed completely,
	# but currently the "install" mode needs it.
	SBOX_TARGET_TOOLCHAIN_DIR=$(dirname "$SBOX_CROSS_GCC_DIR")

	if [ -z "$SBOX_MODE_PATH" ]; then
		# /sb2/wrappers and /sb2/scripts contain utilities for
		# development support, and are available in the
		# software development modes ("simple" and "devel")
		export PATH=/sb2/wrappers:/sb2/scripts:$HOME/.scratchbox2/$SBOX_TARGET/bin:$SBOX_DIR/bin:$PATH:/sbin:/usr/sbin:$SBOX_TARGET_ROOT/bin:$SBOX_TARGET_ROOT/usr/bin:$SBOX_TARGET_ROOT/usr/local/bin
	else
		export PATH=$SBOX_MODE_PATH
	fi

	# LD_PRELOAD will be set to SBOX_LIBSB2 by sb2-monitor.

	export PS1="[SB2 $SBOX_MAPMODE $SBOX_TARGET] \u@\h \W \$ "
}


function initialize_sb_logging()
{
	cmd_param=$1
	args_param=$2
	if [ "$SBOX_MAPPING_LOGLEVEL" != "" ]; then
		tstamp=`SBOX_DISABLE_MAPPING=1 /bin/date +%Y%m%d-%H%M`
		if [ ! -d $HOME/sb2_logs ]; then
			SBOX_DISABLE_MAPPING=1 mkdir $HOME/sb2_logs 
			echo "Created directory $HOME/sb2_logs for log files"
		fi
		MAPPING_LOGFILE=$HOME/sb2_logs/$cmd_param.$tstamp.$$.log
		export SBOX_MAPPING_LOGFILE=$MAPPING_LOGFILE

		if [ "$SBOX_MAPPING_DEBUG" == "1" ]; then
			# log command:
			echo "##Log from $cmd_param $args_param" >$MAPPING_LOGFILE

			# log initial environment if logging is enabled
			env | sed -e 's/^/#/' >>$MAPPING_LOGFILE
			echo "#SBOX_TARGET_ROOT=$SBOX_TARGET_ROOT" >>$MAPPING_LOGFILE
			echo "#SBOX_TOOLS_ROOT=$SBOX_TOOLS_ROOT" >>$MAPPING_LOGFILE
			echo "#SBOX_MAPMODE=$SBOX_MAPMODE" >>$MAPPING_LOGFILE

			echo "Running scratchbox with these settings:"
			echo "SBOX_LIBSB2 = $SBOX_LIBSB2"
			echo "SBOX_LUA_SCRIPTS = $SBOX_LUA_SCRIPTS"
			echo "SBOX_TOOLS_ROOT = $SBOX_TOOLS_ROOT"
			echo "SBOX_TARGET_ROOT = $SBOX_TARGET_ROOT"
			echo "SBOX_MAPPING_LOGFILE = $SBOX_MAPPING_LOGFILE"
			echo "SBOX_MAPPING_LOGLEVEL = $SBOX_MAPPING_LOGLEVEL"
			echo
		fi
	fi
}

#
# Write variables to $SBOX_SESSION_DIR/sb2-session.conf
# NOTE: this file will be read by lua interpreter and the shell,
# so only simple string assignments are allowed! 
# (even comments are different in Lua and shell scripts..)
function create_common_sb2_conf_file_for_session()
{
	sbox_user_home_dir=$HOME
	if [ -z "$HOME" ]; then
		sbox_user_home_dir="/home/unknown_user"
	fi

	cat <<END >>$SBOX_SESSION_DIR/sb2-session.conf
comment_1=" Common configuration file for Lua and Shell scripts."
comment_2=" Automatically generated file, do not edit."

sbox_target="$SBOX_TARGET"

sbox_dir="$SBOX_DIR"
sbox_workdir="$SBOX_WORKDIR"
sbox_user_home_dir="$sbox_user_home_dir"
sbox_target_toolchain_dir="$SBOX_TARGET_TOOLCHAIN_DIR"

sbox_mapmode="$SBOX_MAPMODE"
sbox_mode_specific_options="$SBOX_MODE_SPECIFIC_OPTIONS"
sbox_target_root="$SBOX_TARGET_ROOT"
sbox_cloned_target_root="$SBOX_CLONED_TARGET_ROOT"
sbox_tools_root="$SBOX_TOOLS_ROOT"
sbox_temp_dpkg_admin_dir="$SB2_TEMP_DPKG_ADMIN_DIR"

sbox_cpu="$SBOX_CPU"
sbox_cputransparency_method="$SBOX_CPUTRANSPARENCY_METHOD"
sbox_sbrsh_config="$SBRSH_CONFIG"

sbox_host_gcc_prefix_list="$SBOX_HOST_GCC_PREFIX_LIST"
sbox_host_gcc_dir="$SBOX_HOST_GCC_DIR"
sbox_extra_host_compiler_args="$SBOX_EXTRA_HOST_COMPILER_ARGS"
sbox_host_gcc_subst_prefix="$SBOX_HOST_GCC_SUBST_PREFIX"
sbox_block_host_compiler_args="$SBOX_BLOCK_HOST_COMPILER_ARGS"

sbox_uname_machine="$SBOX_UNAME_MACHINE"
sbox_libsb2="$SBOX_LIBSB2"

sbox_emulate_sb1_bugs="$SBOX_EMULATE_SB1_BUGS"
END
}

# create $SBOX_SESSION_DIR/gcc-conf.lua
function create_gcc_conf_file_for_session()
{
	gcc_config_files=`ls ~/.scratchbox2/$SBOX_TARGET/sb2.config.d/gcc.config*.lua 2>/dev/null`
	if [ -n "$gcc_config_files" ] ; then
		# Create the configuration file. Do some variable substitutions:
		# "extra_cross_compiler_args" and "extra_cross_ld_args"
		# need absolute paths to the orig. rootstrap location, at least.
		cat $gcc_config_files | \
			sed -e "s:@SBOX_TARGET_ROOT@:$SBOX_TARGET_ROOT:g" \
			>$SBOX_SESSION_DIR/gcc-conf.lua
	fi
}

# write_ld_library_path_replacement_to_exec_config():
#
# Create replacement for LD_LIBRARY_PATH and write it to the created config
# file. This is called first for the tools (tools_root), and if host CPU
# type == target CPU, then this is called again to create settings for
# target_root as well.
#
# This also locates a libsb2.so.1 library which must be used; Several
# possible locations are checked. Tools/target need to get the libsb2.so
# library from a "neutral" place so that it would be possible to
# upgrade/downgrade any component (tools,target_roots or sb2 itself)
# without having to re-configure other components in the system.
function write_ld_library_path_replacement_to_exec_config()
{
	rootdir=$1
	varname=$2
	shift 2
	libsb2_candidates="$@"

	# Build replacement for LD_LIBRARY_PATH:

	# ---- Step 1. Location of libsb2.so
	libsb2_dirname=""
	libsb2_path=""
	if [ -n "$libsb2_candidates" ]
	then
		for l in $libsb2_candidates
		do
			if [ -f $l ]
			then
				# IMPORTANT: $libsb2_dirname and $libsb2_path
				# will be used by
				# write_libsb2_and_ld_so_state_to_exec_config()
				libsb2_dirname=`dirname $l`
				libsb2_path=$l
				break
			fi
		done
	fi

	# ---- Step 2. Directories under $rootdir
	# First, make sure that libsb2 is searched
	liblocations="$SBOX_DIR/lib/libsb2 /usr/lib/libsb2"

	# Include directories listed in ld.so.conf
	if [ -f $rootdir/etc/ld.so.conf ]; then
		lloc2=`egrep '^/' $rootdir/etc/ld.so.conf`
		liblocations="$liblocations $lloc2"
	fi
	# Include directories listed in ld.so.conf.d/*
	if [ -d $rootdir/etc/ld.so.conf.d ]; then
		lloc2=`cat $rootdir/etc/ld.so.conf.d/* 2>/dev/null | egrep '^/'`
		liblocations="$liblocations $lloc2"
	fi

	# Next, force libfakeroot to be searced:
	liblocations="$liblocations /usr/lib/libfakeroot \
		/usr/lib64/libfakeroot /usr/lib32/libfakeroot"

	# Find all directories that are used in the ld.so cache file:
	if [ -x $rootdir/sbin/ldconfig ]; then
		# print contents of the cache, take destination
		# names (the part after "=>"), drop file names (leave
		# directory names, and remove duplicates:
		dirs_in_cache=`$rootdir/sbin/ldconfig -p \
			-C $rootdir/etc/ld.so.cache | 
			fgrep '=>' | 
			sed -e 's/^.*=> //' -e 's:/[^/]*$::' | 
			sort | uniq`
		ld_library_extras_from_cache=$dirs_in_cache
		liblocations="$liblocations $dirs_in_cache"
	fi

	# Create the variable.
	echo "$varname =" >>$SBOX_SESSION_DIR/exec_config.lua
	colon=""
	if [ -n "$libsb2_dirname" ]; then
		echo " \"$colon$libsb2_dirname\" .." >>$SBOX_SESSION_DIR/exec_config.lua
		colon=":"
	fi
	for l in $liblocations; do
		if [ -d $rootdir$l ]; then
			echo " \"$colon$rootdir$l\" .." >>$SBOX_SESSION_DIR/exec_config.lua
			colon=":"
		fi
	done

	# Last, the default locations:
	# (these may be already included by the previous step)
	echo " \"$colon$rootdir/lib\" .." >>$SBOX_SESSION_DIR/exec_config.lua
	colon=":"
	echo " \"$colon$rootdir/usr/lib\" .." >>$SBOX_SESSION_DIR/exec_config.lua

	# Finalize the library search path.
	echo " \"\"" >>$SBOX_SESSION_DIR/exec_config.lua
}

# Test if qemu has "-0 argv0" and "-E envvar=value" flags, and/or
# "-libattr-hack"
function check_qemu_features()
{
	qemu_path=$1

	test_output=`$qemu_path -h | grep '^-0'`
	if [ -n "$test_output" ]; then
		# -0 is supported
		conf_cputransparency_has_argv0_flag="true"
	else
		conf_cputransparency_has_argv0_flag="false"
	fi

	test_output=`$qemu_path -h | grep '^-E'`
	if [ -n "$test_output" ]; then
		# -E is supported
		conf_cputransparency_qemu_has_env_control_flags="true"
	else
		conf_cputransparency_qemu_has_env_control_flags="false"
	fi

	test_output=`$qemu_path -h | grep '^-libattr-hack'`
	if [ -n "$test_output" ]; then
		conf_cputransparency_qemu_has_libattr_hack_flag="true"
	else
		conf_cputransparency_qemu_has_libattr_hack_flag="false"
	fi
}

# Test if the "--argv0" flag is supported by the ld.so
function check_ld_so_argv0_feature()
{
	rootdir=$1
	ld_so_path=$2

	ld_so_argv_flag_works="false" # the default

	# Executing ld.so without any arguments should print 
	# usage information to stderr:
	test_output=`$ld_so_path 2>&1 | grep 'argv0 STRING'`
	if [ -n "$test_output" ]; then
		# description about --argv0 exists!
		ld_so_argv_flag_works="true"
	fi
}

function write_libsb2_and_ld_so_state_to_exec_config()
{
	rootdir=$1
	sb2_installed_varname=$2
	sbox_dir_varname=$3
	ld_so_path_varname=$4
	ld_so_supports_argv0_varname=$5
	libsb2_dir_varname=$6

	# Check if ld.so can be used from $rootdir by 
	# checking that libsb2 has been installed to tools

	if [ -d $rootdir/$SBOX_DIR/lib/libsb2 ]; then
		sbox_dir_2=$rootdir/$SBOX_DIR
	elif [ -d $rootdir/usr/lib/libsb2 ]; then
		sbox_dir_2=$rootdir/usr
	else
		sbox_dir_2=""
	fi

	if [ -z "$libsb2_path" ]; then
		libsb2_path=$sbox_dir_2/lib/libsb2/libsb2.so.1
		libsb2_dirname=""
	fi

	if [ -f $libsb2_path ]; then
		libsb2_dir=`/usr/bin/dirname $libsb2_path`
		echo "-- $libsb2_path" >>$SBOX_SESSION_DIR/exec_config.lua
		echo "$libsb2_dir_varname = \"$libsb2_dir\"" \
		    >>$SBOX_SESSION_DIR/exec_config.lua
		echo "$sb2_installed_varname = true" \
		    >>$SBOX_SESSION_DIR/exec_config.lua
		ld_so_found="yes"
	else
		echo "$sb2_installed_varname = false" >>$SBOX_SESSION_DIR/exec_config.lua
		ld_so_found="no"
	fi

	echo "$sbox_dir_varname = \"$sbox_dir_2\"" >>$SBOX_SESSION_DIR/exec_config.lua

	# check the dynamic linker:

	# First try if the default linker can be used
	ld_so_candidate=$rootdir/lib/ld-linux.so.2
	if [ -f $ld_so_candidate ]; then
		check_ld_so_argv0_feature $rootdir $ld_so_candidate
		if [ "$ld_so_argv_flag_works" != "true" ]; then
			# the default ld.so does not support --argv0.
			# Find out if a replacement has been installed for sb2.
			ld_so_with_version=`readlink $ld_so_candidate`

			# First try if it exists in the same directory where
			# libsb2.so is:
			ld_so_candidate2=$libsb2_dirname/$ld_so_with_version
			if [ -n "$libsb2_dirname" -a -f $ld_so_candidate2 ]; then
				check_ld_so_argv0_feature $rootdir \
					$ld_so_candidate2

				if [ "$ld_so_argv_flag_works" == "true" ]; then
					ld_so_candidate=$ld_so_candidate2
				fi # else keep the default ld_so_candidate
			fi

			if [ "$ld_so_argv_flag_works" != "true" ]; then
				ld_so_candidate2=$SBOX_DIR/lib/libsb2/$ld_so_with_version
				if [ -f "$ld_so_candidate2" ]; then
					check_ld_so_argv0_feature $rootdir \
						$ld_so_candidate2
					if [ "$ld_so_argv_flag_works" == "true" ]; then
						ld_so_candidate=$ld_so_candidate2
					fi # else keep the default ld_so_candidate
				fi # no replacement, use the default ld.so. No --argv0
			fi
		fi
	else
		#
		# There is no dynamic linker in target rootstrap.  We
		# still check whether it is installed in the same place
		# where libsb2 for this target was found.  This is special
		# case that is normally used when building rootstraps
		# because they don't have dynamic linker installed
		# into rootstrap (yet).
		#
		# Note that we need to have symlink ld-linux.so.2 that
		# points to the actual dynamic linker since we don't
		# know its version.
		#
		ld_so_candidate2="$libsb2_dirname/ld-linux.so.2"
		if [ -L $ld_so_candidate2 ]; then
			ld_so_candidate2=`/bin/readlink -f $ld_so_candidate2`
			# check also that it has --argv0 support
			check_ld_so_argv0_feature $rootdir $ld_so_candidate2
			if [ "$ld_so_argv_flag_works" == "true" ]; then
				ld_so_candidate=$ld_so_candidate2
				ld_so_argv_flag_works="true"
			else
				ld_so_candidate=""
				ld_so_argv_flag_works="false"
			fi
		else
			ld_so_candidate=""
			ld_so_argv_flag_works="false"
		fi
	fi

	if [ -n "$SBOX_OPT_Z_NO_LD_SO_EXEC" ]; then
		ld_so_candidate=""
		ld_so_argv_flag_works="false"
	fi

	if [ -n "$ld_so_candidate" ]; then
		echo "$ld_so_path_varname = \"$ld_so_candidate\"" >>$SBOX_SESSION_DIR/exec_config.lua
		echo "$ld_so_supports_argv0_varname = $ld_so_argv_flag_works" >>$SBOX_SESSION_DIR/exec_config.lua

	else
		echo "$ld_so_path_varname = nil" >>$SBOX_SESSION_DIR/exec_config.lua
		echo "$ld_so_supports_argv0_varname = false" >>$SBOX_SESSION_DIR/exec_config.lua
	fi
}

#
# write_locale_paths_to_exec_config()
#
# Probes localization files and directories and writes
# it to exec_config.lua.
#
function write_locale_paths_to_exec_config()
{
	rootdir=$1
	generated_locale_path=$2
	locale_path_varname=$3

	#
	# Check whether $rootdir has localization files
	# in archived or extracted format.  If they are
	# in extracted format, we can use files straight
	# from $rootdir.  Otherwise we need to use extracted
	# files that were created by sb2-generate-locales and
	# placed under $locale_path.
	#
	locale_path="$rootdir/usr/lib/locale"
	if [ -d "$locale_path" ]; then
		if [ -f "$locale_path/locale-archive" ]; then
			# need to use generated files
			locale_path="$generated_locale_path"
		fi
		echo "$locale_path_varname = \"$locale_path\"" \
		    >> $SBOX_SESSION_DIR/exec_config.lua
	else
		echo "$locale_path_varname = nil" \
		    >> $SBOX_SESSION_DIR/exec_config.lua
	fi
}

# Write configuration file $SBOX_SESSION_DIR/exec_config.lua
function create_exec_config_file()
{
	cat >$SBOX_SESSION_DIR/exec_config.lua <<END
-- exec settings. Automatically generated file, do not edit.
END

	library_interface=`LD_LIBRARY_PATH=$SBOX_DIR/lib/libsb2:$LD_LIBRARY_PATH sb2-show libraryinterface`

	# 1. Exec settings for tools
	if [ "$SBOX_TOOLS_ROOT" != "" ]; then
		tools_basename=`basename $SBOX_TOOLS_ROOT`
		write_ld_library_path_replacement_to_exec_config \
			$SBOX_TOOLS_ROOT conf_tools_ld_so_library_path \
			$SBOX_DIR/lib/libsb2/tools/$tools_basename/$library_interface/libsb2.so.1 \
			$SBOX_DIR/lib/libsb2/tools/$library_interface/libsb2.so.1 \
			$SBOX_TOOLS_ROOT/usr/lib/libsb2/libsb2.so.1

		write_libsb2_and_ld_so_state_to_exec_config \
			$SBOX_TOOLS_ROOT \
			conf_tools_sb2_installed conf_tools_sbox_dir \
			conf_tools_ld_so conf_tools_ld_so_supports_argv0 \
			conf_tools_libsb2_dir

		write_locale_paths_to_exec_config \
			$SBOX_TOOLS_ROOT \
			$HOME/.scratchbox2/$tools_basename/locales \
			conf_tools_locale_path

		if [ ld_so_found != "yes" ]; then
			# ld.so from tools can not be used. Add tools' shared
			# library locations to the normal LD_LIBRARY_PATH;	
			# this is risky but the best what we can do now
			# (these extra locations must be after other locations
			# in LD_LIBRARY_PATH => ld_library_path_extras won't
			# be added to LD_LIBRARY_PATH here, but later)
			echo $ld_library_extras_from_cache |
				sed -e s:^:$rootdir:g -e "s; ;:$rootdir;g" \
				>$SBOX_SESSION_DIR/ld_library_path_extras
		fi
	else
		# SBOX_TOOLS_ROOT was empty, tools will be used from
		# host environment.
		cat <<END >>$SBOX_SESSION_DIR/exec_config.lua
conf_tools_ld_so_library_path = nil
conf_tools_sb2_installed = false
conf_tools_sbox_dir = ""
conf_tools_ld_so = nil
conf_tools_ld_so_supports_argv0 = false
conf_tools_libsb2_dir = nil
conf_tools_locale_path = nil
END
	fi

	# 2. Exec settings for rootstrap
	conf_cputransparency_has_argv0_flag="false"
	conf_cputransparency_qemu_has_env_control_flags="false"
	conf_cputransparency_qemu_has_libattr_hack_flag="false"

	if [ "$SBOX_CPUTRANSPARENCY_METHOD" == "" ]; then
		# CPU transparency method has not been set:
		# host CPU == target CPU
		if [ -n "$SBOX_CLONED_TARGET_ROOT" ]; then
			target_basename=`basename $SBOX_CLONED_TARGET_ROOT`
		else
			target_basename=`basename $SBOX_TARGET_ROOT`
		fi

		write_ld_library_path_replacement_to_exec_config \
			$SBOX_TARGET_ROOT conf_target_ld_so_library_path \
			~/.scratchbox2/libsb2/targets/$target_basename/$library_interface/libsb2.so.1 \
			~/.scratchbox2/libsb2/targets/$library_interface/libsb2.so.1 \
			$SBOX_DIR/lib/libsb2/targets/$target_basename/$library_interface/libsb2.so.1 \
			$SBOX_DIR/lib/libsb2/targets/$library_interface/libsb2.so.1 \
			$SBOX_TARGET_ROOT/usr/lib/libsb2/libsb2.so.1

		write_libsb2_and_ld_so_state_to_exec_config \
			$SBOX_TARGET_ROOT \
			conf_target_sb2_installed conf_target_sbox_dir \
			conf_target_ld_so conf_target_ld_so_supports_argv0 \
			conf_target_libsb2_dir

		write_locale_paths_to_exec_config \
			$SBOX_TARGET_ROOT \
			$HOME/.scratchbox2/$SBOX_TARGET/locales \
			conf_target_locale_path
	else
		# SBOX_CPUTRANSPARENCY_METHOD is set empty,
		# host CPU != target CPU
		cat <<END >>$SBOX_SESSION_DIR/exec_config.lua
conf_target_ld_so_library_path = nil
conf_target_sb2_installed = false
conf_target_sbox_dir = ""
conf_target_ld_so = nil
conf_target_ld_so_supports_argv0 = false
conf_target_libsb2_dir = nil
conf_target_locale_path = nil
END

		case "$SBOX_CPUTRANSPARENCY_METHOD" in	
		*qemu*)	check_qemu_features $SBOX_CPUTRANSPARENCY_METHOD
			;;
		esac
	fi

	cat <<END >>$SBOX_SESSION_DIR/exec_config.lua
conf_cputransparency_has_argv0_flag=$conf_cputransparency_has_argv0_flag
conf_cputransparency_qemu_has_env_control_flags=$conf_cputransparency_qemu_has_env_control_flags
conf_cputransparency_qemu_has_libattr_hack_flag=$conf_cputransparency_qemu_has_libattr_hack_flag
END
}

function get_SBOX_SESSION_DIR_from_file()
{
	file=$1

	SBOX_SESSION_DIR=""
	if [ ! -r "$file" ]; then
		exit_error "Failed to read '$file'"
	fi

	if grep -q "# SB2 SessionInfo:" "$file" 2>/dev/null; then
		# $file seems to be valid
		SBOX_SESSION_DIR=`sed -n -e 's/^SBOX_SESSION_DIR=//p' < $file`
		SBOX_TARGET=`sed -n -e 's/^SBOX_TARGET=//p' < $file`
	else
		exit_error "'$file' is not a valid SB2 session information file"
	fi

	if [ ! -d "$SBOX_SESSION_DIR" -o \
	     ! -f $SBOX_SESSION_DIR/.joinable-session ]; then
		exit_error "Session '$SBOX_SESSION_DIR' does not exist"
	fi
	# else the session seems to be valid.
}

# used to select a mapping mode which is distributed with sb2.
function add_map_mode()
{
	if [ -z "$SBOX_MAPMODE" ]; then
		# SBOX_MAPMODE was not set, this will be the default mode.
		# Note that more than one mapping mode can be defined only
		# when a persistent session is created (opt. -S)
		SBOX_MAPMODE=$1
	else
		if [ -z "$SB2_INTERNAL_MAPMODES" ]; then
			SB2_INTERNAL_MAPMODES="$SBOX_MAPMODE"
		fi
	fi

	SB2_INTERNAL_MAPMODES="$SB2_INTERNAL_MAPMODES $1"
	NUM_MAPMODES=`expr $NUM_MAPMODES + 1`
}

function add_external_map_mode()
{
	if [ -z "$SBOX_MAPMODE" ]; then
		# SBOX_MAPMODE was not set. Use basename of the rule file
		# as default mode name:
		SBOX_MAPMODE=`basename $1 .lua`
	fi

	SB2_EXTERNAL_RULEFILES="$SB2_EXTERNAL_RULEFILES $1"
	NUM_MAPMODES=`expr $NUM_MAPMODES + 1`
}

function initialize_new_sb2_session()
{
	# Create a new session
	if [ -n "$SBOX_WRITE_SESSION_INFO_TO_FILE" -a \
	     -f "$SBOX_WRITE_SESSION_INFO_TO_FILE" ]; then
		exit_error "File '$SBOX_WRITE_SESSION_INFO_TO_FILE' already exists."
	fi

	if [ -n "$OPT_SESSION_DIR" ]; then
		# session directory name was specified by an option
		SBOX_SESSION_DIR=$OPT_SESSION_DIR
	else
		# Create session directories
		date_and_time_now=`date +%Y%m%d-%H%M%S`
		SBOX_SESSION_DIR=`mktemp -d /tmp/sb2-$USER-$date_and_time_now.XXXXXX`
		if [ $? != 0 ]; then
			exit_error "Failed to create directory for session (problems with /tmp ?)"
		fi
	fi
	# resolve possible symlinks in SBOX_SESSION_DIR
	SBOX_SESSION_DIR=`readlink -f $SBOX_SESSION_DIR`

	mkdir -p $SBOX_SESSION_DIR
	if [ $? != 0 ]; then
		exit_error "Failed to create directory for session"
	fi
	mkdir $SBOX_SESSION_DIR/tmp
	mkdir $SBOX_SESSION_DIR/proc
	mkdir $SBOX_SESSION_DIR/rules
	mkdir $SBOX_SESSION_DIR/rev_rules

	if [ -n "$SBOX_WRITE_SESSION_INFO_TO_FILE" ]; then
		cat >$SBOX_WRITE_SESSION_INFO_TO_FILE <<END
# SB2 SessionInfo:
SBOX_SESSION_DIR=$SBOX_SESSION_DIR
SBOX_TARGET=$SBOX_TARGET
END
		touch $SBOX_SESSION_DIR/.joinable-session
	fi
}

function join_existing_session()
{
	# Join an existing session, don't create it..
	get_SBOX_SESSION_DIR_from_file "$SBOX_JOIN_SESSION_FILE"

	if [ -n "$SBOX_MAPMODE" ]; then
		# A specific mapping mode was requested by option -m,
		# see if that mode has been made available for this session
		if [ ! -f $SBOX_SESSION_DIR/rules/$SBOX_MAPMODE.lua ]
		then
			exit_error "'$SBOX_MAPMODE' is not a valid mode for this session"
		fi
		# Mode is valid, most probably something else than the
		# default mode for this session. Set an environment variable
		# which will overide the value from the config file.
		export SBOX_SESSION_MODE=$SBOX_MAPMODE
	fi
	if [ -z "$SBOX_TARGET" ]; then
		exit_error "Failed to read SBOX_TARGET from $SBOX_JOIN_SESSION_FILE"
	fi
	OPT_CLONE_TARGET_ROOT="n"
	OPT_CLONE_TARGET_ROOT_FROM=""
}

# create destination for /sb2/wrappers for this session
function link_wrappers_for_mapmode()
{
	w_mode=$1

	if [ -f $SBOX_DIR/share/scratchbox2/modeconf/sb2rc.$w_mode ]; then
		# Get list of wrappers:
		SBOX_WRAPPERS=""
		. $SBOX_DIR/share/scratchbox2/modeconf/sb2rc.$w_mode wrapper_list
		if [ "$SBOX_WRAPPERS" != '' ]; then
			mkdir $SBOX_SESSION_DIR/wrappers.$w_mode

			if [ "$SBOX_WRAPPERS" == 'ALL' ]; then
				ln -s $SBOX_DIR/share/scratchbox2/wrappers/* \
					$SBOX_SESSION_DIR/wrappers.$w_mode
			else
				for ammw in $SBOX_WRAPPERS; do
					if [ -f $SBOX_DIR/share/scratchbox2/wrappers/$ammw ]; then
						ln -s $SBOX_DIR/share/scratchbox2/wrappers/$ammw \
							$SBOX_SESSION_DIR/wrappers.$w_mode
					else
						exit_error "There is no wrapper for $ammw"
					fi
				done
			fi
		fi
	fi
}

function write_configfiles_and_rules_for_new_session()
{
	# creating a new session..
	ln -s $SBOX_LUA_SCRIPTS $SBOX_SESSION_DIR/lua_scripts

	# Create rulefiles and set up wrappers
	if [ -n "$SB2_INTERNAL_MAPMODES" ]; then
		for amm in $SB2_INTERNAL_MAPMODES; do
			ifiles=`ls $SBOX_SESSION_DIR/lua_scripts/pathmaps/$amm/*.lua`
			write_rules_to_session_dir \
				$SBOX_SESSION_DIR/rules/$amm.lua $amm $ifiles

			link_wrappers_for_mapmode $amm
		done
	fi

	if [ -n "$SB2_EXTERNAL_RULEFILES" ]; then
		for ammf in $SB2_EXTERNAL_RULEFILES; do
			amm=`basename $ammf .lua`
			write_rules_to_session_dir \
				$SBOX_SESSION_DIR/rules/$amm.lua $amm $ammf

			# FIXME: Currently it is not possible to specify
			# wrappers with option -M (maybe another option
			# should be added to fix that?)
		done
	fi

	# use a hard link for the rule file name, it is better (faster) than
	# a symlink. "Default.lua" will be loaded, if SBOX_SESSION_MODE is
	# unset (as it is usually)
	ln $SBOX_SESSION_DIR/rules/$SBOX_MAPMODE.lua \
		$SBOX_SESSION_DIR/rules/Default.lua

	create_exec_config_file
	create_common_sb2_conf_file_for_session
	create_gcc_conf_file_for_session

	# Copy intial contents of /var/run from the rootstrap:
	mkdir $SBOX_SESSION_DIR/var
	if [ -d $SBOX_TARGET_ROOT/var ]; then
		(cd $SBOX_TARGET_ROOT/var; find run -depth -print |
			cpio -pamd $SBOX_SESSION_DIR/var 2>/dev/null)
	fi
}

function delete_old_sb2_session()
{
	# Delete a session
	get_SBOX_SESSION_DIR_from_file "$SBOX_DELETE_SESSION_FILE"

	# now we "know" that $SBOX_SESSION_DIR is a directory,
	# but double-checking doesn't hurt before rm -rf..
	if [ -d "$SBOX_SESSION_DIR" ]; then
		rm -rf $SBOX_SESSION_DIR
	fi

	rm "$SBOX_DELETE_SESSION_FILE"
}

my_path=$_
if [ $(basename $my_path) != $(basename $0) ]; then
	my_path=$0
	if [ $(basename $my_path) = $my_path ]; then
		my_path=$(which $my_path)
	fi
fi

SBOX_MAPMODE=""
NUM_MAPMODES=0
SB2_INTERNAL_MAPMODES=""

SBOX_DIR=$(readlink -f $(dirname $(readlink -f $my_path))/..)
SBOX_WORKDIR=$(readlink -f $PWD)
SBOX_SESSION_PERM=""
SBOX_CREATE_REVERSE_RULES="y"
SBOX_MODE_SPECIFIC_OPTIONS=""
OPT_CLONE_TARGET_ROOT="n"
OPT_CLONE_TARGET_ROOT_FROM=""
OPT_SESSION_DIR=""
SBOX_FORCED_TOOLS_ROOT=""

while getopts vdht:em:s:L:Q:M:ZrRS:J:D:W:O:cC:T: foo
do
	case $foo in
	(v) version; exit 0;;
	(d) export SBOX_MAPPING_DEBUG=1
	    export SBOX_MAPPING_LOGLEVEL=debug ;;
	(L) export SBOX_MAPPING_DEBUG=1
	    export SBOX_MAPPING_LOGLEVEL=$OPTARG ;;
	(Q) SBOX_EMULATE_SB1_BUGS=$OPTARG ;;
	(h) usage ;;
	(t) SBOX_TARGET=$OPTARG ;;
	(e) add_map_mode emulate ;;
	(m) add_map_mode $OPTARG ;;
	(M) add_external_map_mode $OPTARG ;;
	(s) SBOX_LUA_SCRIPTS=$OPTARG;;
	(Z) SBOX_OPT_Z_NO_LD_SO_EXEC="y";;
	(r) SBOX_CREATE_REVERSE_RULES="n";;
	(R) SBOX_SESSION_PERM="root";;
	(S) SBOX_WRITE_SESSION_INFO_TO_FILE=$OPTARG ;;
	(J) SBOX_JOIN_SESSION_FILE=$OPTARG ;;
	(D) SBOX_DELETE_SESSION_FILE=$OPTARG ;;
	(W) OPT_SESSION_DIR=$OPTARG ;;
	(O) SBOX_MODE_SPECIFIC_OPTIONS=$OPTARG ;;
	(c) OPT_CLONE_TARGET_ROOT="y" ;;
	(C) OPT_CLONE_TARGET_ROOT_FROM=$OPTARG ;;
	(T) SBOX_FORCED_TOOLS_ROOT=$OPTARG ;;
	(*) usage ;;
	esac
done
shift $(($OPTIND - 1))

if [ -n "$SBOX_SESSION_DIR" -a -f "$SBOX_SESSION_DIR/rules/Default.lua" ]; then
	# already inside an sb2 session; ignore all options and just exec the command.
	echo "WARNING: recursive calls to sb2 are not supported (session already exists)"
	echo "WARNING: going to execute '$*' in this session"
	exec $*
fi

#----------- Check parameters

if [ "$SBOX_MAPPING_DEBUG" == "1" ]; then
	# check that loglevel is valid
	case $SBOX_MAPPING_LOGLEVEL in
	(error|warning|notice|info|debug|noise|noise2|noise3)	;; # OK
	(*) usage ;;
	esac
else
	# default logging level
	export SBOX_MAPPING_LOGLEVEL=warning
fi

if [ -z "$SBOX_WRITE_SESSION_INFO_TO_FILE" ]; then
	# Multiple -m and/or -M options are allowed only
	# when creating a parsistent session
	if [ $NUM_MAPMODES -gt 1 ]; then
		exit_error "Only one of -e, -m or -M is allowed"
	fi
fi

# read commands to execute from stdin - not yet implemented
if [ "$1" = "-" ] ; then
	STDIN=true
fi

# if SBOX_SESSION_PERM is set, export it. It may enable special permissions
# in some mapping modes (e.g. see the "emulate" mode)
if [ -n "$SBOX_SESSION_PERM" ]; then
	export SBOX_SESSION_PERM
	SBOX_FAKEROOT_PREFIX="fakeroot"
fi

if [ -n "$SBOX_FORCED_TOOLS_ROOT" ]; then
	if [ ! -d "$SBOX_FORCED_TOOLS_ROOT" ]; then
		exit_error "Directory $SBOX_FORCED_TOOLS_ROOT does not exist"
	fi
fi

if [ -z "$SBOX_JOIN_SESSION_FILE" ]; then
	# -J was not used
	set_and_check_SBOX_TARGET
	if [ -n "$OPT_SESSION_DIR" ]; then
		case "$OPT_SESSION_DIR" in
		(/*)	;; # OK, absolute
		(*)	exit_error "Option '-W' requires an absolute path"
		esac
		if [ -e "$OPT_SESSION_DIR" ]; then
			exit_error "Option '-W': $OPT_SESSION_DIR exists"
		fi
	fi
else
	# With -J, $SBOX_TARGET *must* come from the session file.
	if [ -n "$SBOX_TARGET" ]; then
		exit_error "Option '-t' can't be used with option '-J'"
	fi
	if [ -n "$OPT_SESSION_DIR" ]; then
		exit_error "Option '-W' can't be used with option '-J'"
	fi
fi

#----------- End of parameter checks

if [ -n "$SBOX_DELETE_SESSION_FILE" ]; then
	delete_old_sb2_session
	exit 0
fi

if [ -n "$SBOX_JOIN_SESSION_FILE" ]; then
	join_existing_session
	set_and_check_SBOX_TARGET
else
	initialize_new_sb2_session
fi

# SBOX_SESSION_DIR needs to be passed in environment variable, always.
export SBOX_SESSION_DIR

sboxify_environment

if [ -z "$SB2_INTERNAL_MAPMODES" -a -z "$SB2_EXTERNAL_RULEFILES" ]; then
	# mapping mode was not specified by an option, SBOX_MAPMODE has been
	# set from the config file by sboxify_environment
	SB2_INTERNAL_MAPMODES=$SBOX_MAPMODE
fi

if [ -z "$SBOX_JOIN_SESSION_FILE" ]; then
	write_configfiles_and_rules_for_new_session
fi

# set the initial binary name for the mapping engine
export __SB2_BINARYNAME="bash"

if [ -n "$SBOX_TOOLS_ROOT" ]; then
	SHELL=$SBOX_TOOLS_ROOT/bin/bash
else
	SHELL=/bin/bash
fi

# Final addition to LD_LIBRARY_PATH, if needed
if [ -f $SBOX_SESSION_DIR/ld_library_path_extras ]; then
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`cat $SBOX_SESSION_DIR/ld_library_path_extras`
fi

# ------------
# Export variables that need to be available in environment;
# don't export anything unnecessary!

export DEB_BUILD_ARCH
export DEB_BUILD_ARCH_CPU
export DEB_BUILD_ARCH_ABI
export DEB_BUILD_GNU_CPU
export DEB_BUILD_GNU_TYPE
export DEB_BUILD_GNU_SYSTEM

export DEB_HOST_ARCH
export DEB_HOST_ARCH_OS
export DEB_HOST_ARCH_CPU

export DEB_HOST_GNU_CPU
export DEB_HOST_GNU_TYPE
export DEB_HOST_GNU_SYSTEM

export LD_LIBRARY_PATH

# ------------
# Now everything is ready, programs can be executed in SB2'ed environment.
# Make automatically generated rules, if needed:
if [ -z "$SBOX_JOIN_SESSION_FILE" ]; then
	#
	# Only generate argvmods rules when we are not joining
	# to session.
	#
	create_argvmods_rules

	# if needed, create path mapping rules for toolchain components.
	# this can only be done after "create_argvmods_rules" has been executed.
	if [ -n "CREATE_ARGVMODS_USR_BIN_RULES" ]
	then
		create_argvmods_usr_bin_rules "$CREATE_ARGVMODS_USR_BIN_RULES"
	fi

	#
	# Create reverse mapping rules before starting the
	# actual command (or shell).
	#
	if [ "$SBOX_CREATE_REVERSE_RULES" == "y" ]; then
		create_reverse_rules
	else
		echo "-- Reverse rules disabled by command line option -r" \
			>$SBOX_SESSION_DIR/rev_rules.note
	fi
fi

#  Initialize logs..
if [ $# -gt 0 -o "$STDIN" = true ] ; then
	initialize_sb_logging $(echo $1 | sed -e 's/\//_/g' -e 's/^\.//') "$args"
else
	initialize_sb_logging sb2
fi

# ------------ cleanup:
# Unset variables which used to be passed in environment,
# but have been moved to sb2-session.conf.
unset SBOX_MAPMODE
unset SBOX_TARGET_ROOT
unset SBOX_CLONED_TARGET_ROOT
unset SBOX_TOOLS_ROOT

# ------------

if [ $# -gt 0 -o "$STDIN" = true ]; then
	binary="$1"
	shift 1
	args="$@"
	exec $SBOX_FAKEROOT_PREFIX sb2-monitor -L $SBOX_LIBSB2 -x $SBOX_DIR/share/scratchbox2/scripts/sb2-exitreport \
		-- $SHELL -c "$binary $args"
else
	exec $SBOX_FAKEROOT_PREFIX sb2-monitor -L $SBOX_LIBSB2 -x $SBOX_DIR/share/scratchbox2/scripts/sb2-exitreport \
		-- $SHELL --noprofile --norc
fi