#!/system/bin/sh

cache_partition=`grep cache /proc/mtd | cut -d: -f1 | sed 's/mtd/mtdblock/'`
mountpoint=`mount | grep ${cache_partition} | awk '{print $3}'` 

# make / writeable so that I can modifications
mount -o rw,remount /

if [ -h /cache ] ; then
  # /cache is a symbolic link
  mkdir /mnt/cache
  mount -t yaffs2 -o rw /dev/block/$cache_partition /mnt/cache
  if [ ! -d /mnt/cache/recovery ] ; then
    mkdir /mnt/cache/recovery
    mv /cache/recovery/* /mnt/cache/recovery/.
  fi
  rm -rf /cache/recovery
  ln -s /mnt/cache/recovery /cache/recovery
elif [ -d /cache ] ; then
  # /cache is a directory
  if [ "$mountpoint" = "/cache" ] ; then
    # /cache is mounted in the right place
    # do nothing, other than permissions at the end of this script
  else
    # the block device is not mounted or, is mounted somewhere else
    umount ${mountpoint}
    mkdir /mnt/cache
    mount -t yaffs2 -o rw /dev/block/$cache_partition /mnt/cache
    if [ ! -d /mnt/cache/recovery ] ; then
       mkdir /mnt/cache/recovery
       mv /cache/recovery/* /mnt/cache/recovery/.
    fi
    rm -rf /cache/recovery
    umount /mnt/cache
    rmdir /mnt/cache
    mount -t yaffs2 -o rw /dev/block/$cache_partition /cache
  fi
elif [ ! -e /cache ] ; then
  # the /cache doesn't exist
  mkdir /cache
  mount -t yaffs2 -o rw /dev/block/${cache_partition} /cache
fi

# change permission to 0.0 so market place can access /cache
chown 0.0 /cache
if [ ! -e /cache/recovery ] ; then
  mkdir /cache/recovery
fi

# change permission for recovery directory so 
# ROM Manager and CWM can access it
chown 1000.2001 /cache/recovery
chmod 0770 /cache/recovery

# back to read-only mode
mount -o ro,remount /
