#!/bin/bash

ME="$0"
if [ -h "$0" ] ; then
	ME=`readlink -f "$0"`
fi

sbinpath=`dirname "$ME"`
if [ "z$sbinpath" = 'z.' ] ; then
	sbinpath=`pwd`
fi

sboxrel=`dirname "$sbinpath"`

SBOX_DIR=`readlink -f $sboxrel`

mode="$1"
SB_GROUP="$2"

LD_HACK="$SBOX_DIR/host_shared/lib/ld.so --library-path $SBOX_DIR/host_shared/lib"

if [ x"$mode" = x ] || [ x"$SB_GROUP" = x ]; then
	echo "Usage: $0 <sudo mode>=yes|no <group>"
	exit 1
fi

umask 0022

# Clean up previous config
rm -f $SBOX_DIR/.run_me_first_done $SBOX_DIR/.sudo_mode

# Create the group if it doesn't exist
if [ x"`getent group $SB_GROUP`" = x ]; then
	echo "Creating group \"$SB_GROUP\"..."
	# sudo doesn't always add /usr/sbin in path
	PATH=$PATH:/usr/sbin groupadd $SB_GROUP
	if [ "$?" -ne 0 ] ; then
		echo "ERROR while creating group: $SB_GROUP"
		exit 1
	fi
fi

# Normal mode
if [ "$mode" = no ]; then
	for i in `cd "$SBOX_DIR" && find . -maxdepth 1 | tr " " "" | grep -ve '^\./\(dev\|users\|ccache\)$' -ve '^\./\?$'` ; do
		I=$SBOX_DIR/`echo $i | tr "" " "`
		chown -R root:root $I
		chmod -R o-w $I
	done

	chown -R root:$SB_GROUP $SBOX_DIR/sbin/*
	chmod 754 $SBOX_DIR/sbin/*
	chmod u+s $SBOX_DIR/sbin/chroot-uid

	if [ ! -e /dev/.udevdb ]; then
		tar cpfl - /dev 2>/dev/null | tar xpfm - -C $SBOX_DIR/
	fi
fi

# Sudo mode
if [ "$mode" = yes ]; then
	chmod -R a+r $SBOX_DIR/*
	for i in `find $SBOX_DIR/ -type d` ; do
		chmod a+x "$i"
	done
	chmod 754 $SBOX_DIR/sbin/*
	mkdir $SBOX_DIR/dev
	echo "$SB_GROUP" > $SBOX_DIR/.sudo_mode
fi

# Common
mkdir -p $SBOX_DIR/ccache
chgrp $SB_GROUP $SBOX_DIR/ccache
chmod 2775 $SBOX_DIR/ccache

chown root:$SB_GROUP $SBOX_DIR/login
chmod 754 $SBOX_DIR/login

# Host system configration for host tools
COPIED=$SBOX_DIR/etc/.copied_files

# Gentoo does not support /etc/hostname
if [ -r /etc/hostname ] ; then
	cp /etc/hostname $SBOX_DIR/etc/
else
	which hostname &> /dev/null
	if [ $? -ne 0 ] ; then
		echo "ERROR: Hostname not available"
		exit 1
	fi
	hostname > $SBOX_DIR/etc/hostname
fi
echo hostname >> "$COPIED"

# hosts file also not present in every installation
if [ -r /etc/hosts ] ; then
	cp /etc/hosts "${SBOX_DIR}/etc"
else
	echo "127.0.0.1 localhost" > "${SBOX_DIR}/etc/hosts"
fi
echo hosts >> "$COPIED"

for file in nsswitch.conf
do
	cp "${SBOX_DIR}/etc/host_etc_base/${file}" "${SBOX_DIR}/etc/"
	echo "$file" >> "$COPIED"
done

for file in resolv.conf host.conf localtime
do
	cp /etc/$file $SBOX_DIR/etc/
	echo $file >> $COPIED
done

for file in `cd /etc && ls -1 *ldap*.conf 2>/dev/null`
do
	cp /etc/$file $SBOX_DIR/etc/
	echo $file >> $COPIED
done

if [ -d /etc/ldap ]; then
	for path in `find /etc/ldap/ -type f`; do
		file=`echo $path | cut -d/ -f3-`
		install -D $path $SBOX_DIR/etc/$file
		echo $file >> $COPIED
	done
fi

mv $COPIED $COPIED.tmp
sort -u $COPIED.tmp > $COPIED
rm $COPIED.tmp

# Target system configuration used for host tools
for link in passwd group fstab mtab
do
	ln -sf /etc/$link $SBOX_DIR/etc/
done

# Done
echo "$SB_GROUP" > $SBOX_DIR/.run_me_first_done
