#!/bin/sh

echo $$ > /var/run/exthost_umount.pid

while [ ! -f "/tmp/.directAccessReady" ]; do
        sleep 1
done

# rewrite unique ID
mkuniqueid > /media/System/id.sys
# tell Qtopia to unload all applets
qcop "QPE/TaskBar" "unloadApplets()"

# give Qtopia some time unload the applets
try=0
while fuser -m -s /progfs ; do
        let try=$try+1
        if [ $try -gt 5 ]; then
                break
        fi
        #echo "Wait ..."
        sleep 1
done

# check is /progfs was idled successfully
if [ $try -gt 5 ]; then
	# no, it wasn't, check if QPE is still using it.
        foundqpe=0
        qpepid=`pidof qpe`
        candpids=`fuser -m /progfs 2>/dev/null | sed -e 's,\([[:digit:]]*\).,\1 ,g'`

        #echo "PID of qpe: $qpepid"
        #echo "PIDs using /progfs: $candpids"

        for i in $candpids; do
                echo "$i eq $qpepid?"
                if [ $i -eq $qpepid ]; then
                	# pity, the qpe process is still using /progfs.
                	# maybe somebody installed a font as IPK?
                        foundqpe=1
                        break
                fi
        done

        if [ $foundqpe -eq 1 ]; then
                #echo "QPE using /progfs, abort"
                # since we cannot just kill qpe, we abort the whole action.
                # delete the lockfiles so that 'exthost' does not interfere
                rm /var/run/exthost_umount.pid
                rm /tmp/.directAccessReady
                qcop "QPE/TaskBar" "reloadApplets()"
                qcop "QPE/System" "postDirectAccess()"
                return
        fi
fi

# 'something' is using /progfs, but it's not qpe, kill it.
fuser -km /progfs
sync
sleep 1

umount /progfs
losetup -d /dev/loop/0

while ! umount /media; do
        sleep 1
done

rm /var/run/exthost_umount.pid
