#!/bin/bash

part_num=1
if test ! -e /dev/block/mmcblk1p$part_num; then
    die "Error: ext sdcard device not found (/dev/block/mmcblk1p$part_num)"
fi

mount -t vfat /dev/block/mmcblk1p$part_num /mnt/external_sdcard >/dev/null 2>&1
echo "Before format:"
busybox df -h /mnt/external_sdcard

(
    cd /mnt/external_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/external_sdcard | awk '{print $2}'
    ); do 
	umount $me >/dev/null 2>&1 
    done
done

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

mount -t vfat /dev/block/mmcblk1p$part_num /mnt/external_sdcard >/dev/null 2>&1
if test -e /mnt/external_sdcard/hello_world.txt; then
    die "Error: no effect formating internal sdcard";
fi

echo
echo "After format:"
busybox df -h /mnt/external_sdcard
