# Script based on http://www.saurik.com/id/10 as well as on
# http://www.elitehardware.de/debian-unter-android-pm-8.html

mnt=$ANDROID_DATA/local/mnt
img=$EXTERNAL_STORAGE/debian.img

unionfs_ko=/mnt/sdcard/lib/modules/2.6.32.9/kernel/fs/unionfs/unionfs.ko

if ! ls $img >&- 2>&-
then
  echo "$img not found. You may re-insert your SD-Card and/or unplug USB"
  exit 1
fi

if ! ls $unionfs_ko >&- 2>&-
then
  echo "$unionfs_ko not found. This kernel module is required."
  exit 1
fi

if ! ls -d /proc/$PPID/status >&- 2>&-
then
  if ! ls /data/local/bin/busybox >&- 2>&-
  then
    echo "/data/local/bin/busybox not found. This script does not run with the android/BSD shell."
    exit 1
  fi
  exec /data/local/bin/busybox ash /data/local/bin/d $* $(getprop net.dns1) $(getprop net.dns2)
fi

if [ "$1" = "u" ]
then
  sync
  for m in $(sed -n 's/^unionfs //p' /proc/mounts|cut -d' ' -f1)
  do
    umount $m
  done
  umount $mnt
  mount -o remount,ro /
  exit
fi

i=0
while true; do
#	echo "now at $i"
	if [ $i -eq 100 ] ; then
#		echo "reached 100"
		break
	fi
	if [ ! -b /dev/block/loop$i ]
	then
		echo "mknod loop$i"
		mknod /dev/block/loop$i b 7 $i
		break
	fi
	i=$(($i+1))
done

#grep -q ^unionfs /proc/modules || /system/bin/insmod ${0%/*}/unionfs.ko
grep -q ^unionfs /proc/modules || /system/bin/insmod $unionfs_ko
grep -q " $mnt " /proc/mounts || mount -o loop,noatime $img $mnt

if [ -d $mnt/debootstrap ]; then
  PATH=/usr/sbin:/usr/bin:/sbin:/bin && chroot $mnt /debootstrap/debootstrap --second-stage
fi

mount -o remount,rw /

#if [ ! -d /tmp ]
#then
#  mkdir /tmp
#  mount -t tmpfs tmpfs /tmp
#fi

for d in $mnt/*
do
  s=/${d##*/}
  [ "$s" = "/etc" ] && s=/system/etc
  if [ ! -h $s ] && [ -d $d ]
  then
    if ! cut -d' ' -f2 /proc/mounts|grep -q \^$s\$
    then
if [ "$s" = "/mnt" ]
then
echo "s=/mnt"
else
      if [ -d $s ]
      then
        mount -t unionfs -o dirs=$d=rw:$s=ro unionfs $s
      else
        ln -s $d $s
      fi
fi
    fi
  fi
done

# Fix empty sources.list for 'apt-get update'
#if [ ! -s $mnt/apt/sources.list ]
#then
#  cat<<EOF>$mnt/etc/apt/sources.list
#deb http://ftp.de.debian.org/debian lenny main
#deb-src http://ftp.de.debian.org/debian lenny main
#EOF
#fi

echo "nameserver $1" >/etc/resolv.conf
echo "nameserver $2" >>/etc/resolv.conf

# If no /etc/mtab, the debian mount command shows nothing
[ -f /etc/mtab ] || ln -s /proc/mounts /etc/mtab

# Note: Mounting readonly triggers a bug in dpkg currently
# rmdir("//..dpkg-tmp") = -1 EROFS (Read-only file system)
#mount -o remount,ro /

#if [ -f /etc/initdeb ]
#then
#  echo "running /etc/initdeb"
#  /etc/initdeb
#else
#  echo "creating /etc/initdeb"
#  touch /etc/initdeb
#  chmod +x /etc/initdeb
#fi

export PATH=/usr/sbin:/usr/bin:/sbin:/bin
export TERM=xterm
export HOME=/root
exec /bin/bash --login
