#!/bin/sh

function record_ipk()
{
    pkg=$1
    extname=${pkg##*.}
    local recorded=0
    if [ "$extname" == "ipk" ]; then
        mkdir -p /tmp/ipk_tmp
        tar -xzf $pkg -C /tmp/ipk_tmp
        tar -xzf /tmp/ipk_tmp/control.tar.gz -C /tmp/ipk_tmp/
        pkg_name=`cat /tmp/ipk_tmp/control | grep "Package" | awk -F : '{
print $2}' | sed 's/ //g' | tr '\n' '\0'`
        rm -rf /tmp/ipk_tmp
    else
        pkg_name=$pkg
    fi

    if [ -f "/app/config/ipk_installed" ]; then
        for line in `cat /app/config/ipk_installed | awk '{print $1}'`
        do
            if [ "$line" == "$pkg_name" ]; then
                recorded=1
                break
            fi
        done
    fi
    if [ "$recorded" -eq "0" ]; then
        if [ "$extname" == "ipk" ]; then
            echo "$pkg_name install $pkg_name" >> /app/config/ipk_installed
        else
            echo "$*" >> /app/config/ipk_installed
        fi
    fi
}

function remove_ipk()
{
    pkg=$1
    sed -i "/^$pkg /d" /app/config/ipk_installed
}

index=0
for arg in $*
do
    echo "arg $arg"
    first=${arg:0:1}
    if [ "$first" == "-" ]
    then
        echo "skip $arg"
        continue
    fi
    let index+=1
    if [ "$index" == "1" ]
    then
      sub_cmd=$arg
    elif [ "$index" == "2" ]
    then
      pkg=$arg
    fi
done
echo "cmd is $sub_cmd pkg is $pkg"

args="$*"
/bin/opkg $*
sync

if [ "$?" == 0 ]
then
    if [ "$sub_cmd" == "install" ] 
    then
        echo "install $pkg success"
        record_ipk $pkg $args
    elif [ "$sub_cmd" == "remove" ]
    then
        echo "remove $pkg success"
        remove_ipk $pkg
    fi
else
    echo "run failed $args"
fi

