#!/bin/bash

if [ $$ != 1 ]; then
	echo 'must be container init'
	exit 1
fi
hostname $1

#umount -a -t tmpfs > /tmp/a 2>&1

vardir=/var/lib/crdemo/$1
mkdir -p $vardir/tmp
mount --bind $vardir/tmp /tmp

# Give screen its own private /var/run/screen
screendir=$vardir/screen
mkdir $screendir
mount --bind $screendir /var/run/screen

exec 0<&-
exec 0</dev/null

exec 1>&-
exec 1>nohup.out
exec 2>&-
exec 2>nohup.out

#for f in `/bin/ls /proc/self/fd`; do
	#echo reopening $f as $d
	#d=`readlink /proc/$$/fd/$f`
	#exec $f<&-
	#exec $f<$d
#done

cgroupdir=/cgroup/$1
mkdir -p $cgroupdir
echo $$  > $cgroupdir/tasks
#mount -t proc proc /proc
#mount -t devpts -o newinstance,ptmxmode=666 pts2 /dev/pts

touch $vardir/container_waiting

# wait for parent to pass us our network device
while [ ! -f $vardir/devready ]; do
	sleep 1
done

a0=`head -2 $vardir/addr | tail -1`
d1=`head -3 $vardir/addr | tail -1`
a1=`head -4 $vardir/addr | tail -1`
ip link set $d1 name eth0
ifconfig eth0 $a1 up
route add -host $a0 gateway $a1
ifconfig -a > /root/list

/usr/sbin/sshd

pid=$!
touch $vardir/container_ready
while [ -d /proc/$pid ]; do
	sleep 20
done
echo "sshd (pid $pid) exited, container is now exiting"
exit 0
