#/bin/bash

# if we're not running on the imager, bail out

if [ "$MIC_RUN" = "" ]; then
	echo "Not initializing tracker index on device"
	exit 0
fi

# start tracker, and wait until it's ready
tracker daemon --start
COUNT=0
while [ "`tracker daemon  | grep 'File System' | gawk '{ print $9 }'`" = "Initializing" ]; do
    if [ $COUNT -eq 60 ]; then
        echo "Tracker init takes too long, bailing out. final status: "
        tracker daemon
        break
    fi
    echo "Tracker miners initializing, waiting..."
    sleep 1
    let COUNT=COUNT+1
done

# kick tracker indexer for each file on the device, just to be safe
for D in PICTURES MUSIC VIDEOS; do
    UD=`xdg-user-dir $D`
    find $UD -type f -exec tracker index --file '{}' \;
done

# wait until tracker miners are idle
tracker-control -S
COUNT=0
while [ "`tracker daemon  | grep 'File System' | gawk '{ print $9 }'`" != "Idle" ]; do
    if [ $COUNT -eq 60 ]; then
        echo "Tracker shutdown takes too long, bailing out. final status: "
        tracker daemon
        break
    fi
    echo "Tracker miners busy, waiting..."
    sleep 1
    let COUNT=COUNT+1
done

# give a list of indexed files for the mic log
if [ -n "$MIC_RUN" ]; then
    tracker search -i
fi

# and kill the beast
tracker daemon --terminate=all
