#!/bin/sh

# CheckApp=true
CheckApp=false

# If booting, wait until rcS script finishes
tries=0
pidof rcS > /dev/null
while [ $? = 0 -a $tries -lt 60 ] ; do
    sleep 1
    tries=`expr $tries + 1`
    pidof rcS > /dev/null
done

uname -r | grep mipsisa32r2el > /dev/null 2>&1
if [ $? = 0 ] ; then
    PROD=qvpro
    OTHER_PKGS='/media/sd*/netfilter-*.pkg /media/sd*/libc-*.pkg'
else
    PROD=qvavc
fi
KERNEL="/media/sd*/$PROD-kernel-*.pkg"
if [ "$PROD" = qvpro ] ; then
    ifconfig eth1 > /dev/null 2>&1
    [ $? != 0 ] && KERNEL="/media/sd*/qvenc-kernel-*.pkg"
fi

VER_FILE=/qvidium/qvidium-mpegipcodec.ver

if [ -f $VER_FILE -a $CheckApp = true ] ; then
    APP_VER=`head -1 $VER_FILE | cut -d- -f2`
    for file in /media/sd*/$PROD-app-$APP_VER.pkg
    do
        if [ -f $file ] ; then
            echo "App version $APP_VER already installed" > /dev/console
            exit 0
        fi
    done
fi

REBOOT=false
for file in $KERNEL \
            /media/sd*/$PROD-rootfs-*.pkg \
            /media/sd*/$PROD-app-*.pkg $OTHER_PKGS 
do
    if [ -f $file ] ; then
        cd /tmp
        tar xvf $file > /dev/console 2>&1
        sh install.sh > /dev/console 2>&1
        REBOOT=true
    fi
done

[ $CheckApp = false ] && mv $0 $0.resetSoftware.sh

if [ $REBOOT = true ] ; then
    echo "Rebooting..." > /dev/console
    reboot
fi