#!/bin/bash

part_num=$(grep -e '^dev_mount internal_sdcard' /etc/vold.fstab | awk '{print $4}')
mount -t vfat /dev/block/mmcblk0p$part_num /mnt/sdcard >/dev/null 2>&1
echo "Before format:"
busybox df -h /mnt/sdcard

(
    cd /mnt/sdcard
    touch hello_world.txt
)


for try in $(seq 1 3); do
    for me in $(
	mount | grep -e "vold.*:$part_num" | awk '{print $2}'
	mount | grep /mnt/sdcard | awk '{print $2}'
    ); do 
	umount $me >/dev/null 2>&1 
    done
done

if mount | grep -q /mnt/sdcard; then
    die "Can not umount internal sdcard (maybe some process is visiting it):
$(ps $(fuser -m /mnt/sdcard)|tail -n 1)"
fi
mkfs.vfat /dev/block/mmcblk0p$part_num

mount -t vfat /dev/block/mmcblk0p$part_num /mnt/sdcard >/dev/null 2>&1
if test -e /mnt/sdcard/hello_world.txt; then
    die "Error: no effect formating internal sdcard";
fi
echo "After format:"
busybox df -h /mnt/sdcard
