#!/usr/bin/env sh
# ipkg-wrapper
#
# This is a wrapper script for ipkg. The script performs various functions when called from the following valid symlinks:
#   ipkg-files  -   lists the files in the given package.
#   ipkg-info   -   shows the info of the given package.
#   ipkg-size   -   calculates the installed size of the given package. Note that the calculated size can be different from
#                   the file versus an installed package due to differences in block size, the size that ls returns rather
#                   than what's recorded in the package, the phase of the moon, etc. IOW, don't sweat the small stuff!
#
# 2005-05-09 GROG! <Uber[dot]GROG[at]Gmail[dot]Com>: Written
# 2005-06-02 GROG! <Uber[dot]GROG[at]Gmail[dot]Com>: Updated to use du if ls doesn't rerurn size.

# set -x # TESTING

if [ $# -ne 1 ]; then
    echo "Usage: ${0##*/} (pkgname|pkgfile)" >&2
    exit 1
fi

ACTION=${0##*-}

case $ACTION in
    size) if [ -s $1 ]; then
              ipkg-files $1 2>/dev/null |
                while read line; do
                    set -- $line
                    echo $3
                done
          else
              LISTSIZE=$(set -- $(ls -l $(which ${0##*/})); echo $#)
              if [ $LISTSIZE -ge 9 ]; then
                  ipkg-files $1 | xargs ls -l 2>/dev/null |
                    while read line; do
                        set -- $line
                        echo $5
                    done
              else
                  ipkg-files $1 | xargs du 2>/dev/null |
                    while read line; do
                        set -- $line
                        echo $(($1*1024))
                    done
              fi
          fi | (while read size; do
                    TOTALSIZE=$((TOTALSIZE+$size))
                done
                echo "Total installed size: $((TOTALSIZE/1024))kb")
          ;;
    files|info)
          if [ -s $1 -a ! -d $1 ]; then
            TMPDIR=/tmp/${1##*/}
            TMPDIR=${TMPDIR%%_*}
            \mkdir $TMPDIR >/dev/null
            \cp $1 $TMPDIR >/dev/null
            \cd $TMPDIR >/dev/null
            (ar -xv $1 || tar -xzf $1) >/dev/null 2>&1
            case $ACTION in
                files) echo "File listing of package file $1:" >&2
                       tar -tzvf data.tar.gz
                       ;;
                 info) tar -xzf control.tar.gz
                       cat control
                       echo
                       ;;
            esac
            cd - >/dev/null
            rm -Rf $TMPDIR >/dev/null
          else
            ipkg $ACTION $1
          fi
          ;;
    *) echo "This script must be called via one of the following symlink's:" >&2
       echo "    ipkg-files ipkg-info ipkg-size" >&2
       exit 1 ;;
esac

exit 0

