# 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=/dev/block/mmcblk0p2

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

echo "\$0=$0"
#exit 1

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 $0 $* $(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

grep -q ^unionfs /proc/modules || /system/bin/insmod $unionfs_ko
grep -q " $mnt " /proc/mounts || mount -o noatime -t ext3 $img $mnt

#mount -o remount,rw /

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

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

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