#!/bin/sh

. config/options

get_meta $1

mkdir -p $ROOTFS/var/lib/opkg/info/
STAMP=$ROOTFS/var/lib/opkg/info/$1.control
PACKAGE=$PKGROOT/$PKG_OPK

# check for platform-specific package overlay
INSTALL_RULE=$PACKAGES/$1/install
PLATFORM_INSTALL="$PLATFORM_PACKAGES/$1/install"
[ -r "$PLATFORM_INSTALL" ] && INSTALL_RULE="$PLATFORM_INSTALL"
MACHINE_INSTALL="$MACHINE_PACKAGES/$1/install"
[ -r "$MACHINE_INSTALL" ] && INSTALL_RULE="$MACHINE_INSTALL"

# check for flavour-specific package overlay
FLAVOUR_INSTALL="$FLAVOUR_PACKAGES/$1/install"
[ -r "$FLAVOUR_INSTALL" ] && INSTALL_RULE="$FLAVOUR_INSTALL"

if [ ! -f $INSTALL_RULE ]; then
  echo "$1 is not a runtime package, skipping..." >&$VERBOSE_OUT
  exit 0
fi

if [ -f $STAMP ]; then
  if [ $PACKAGES/$1/unpack -nt $STAMP -o $PACKAGES/$1/patches -nt $STAMP ] || [ $PACKAGES/$1/build -nt $STAMP ]; then
    $SCRIPTS/clean $1
  elif [ $INSTALL_RULE -nt $STAMP ]; then
    $SCRIPTS/unpackage $1
  fi

  [ -f $PACKAGE -a $PACKAGE -nt $STAMP ] && $SCRIPTS/uninstall $1
fi

if [ -f $STAMP ]; then
  echo "$1 already installed, skipping..." >&$VERBOSE_OUT
  exit 0
fi

printf "%${INDENT}c INSTALL  $1\n" >&$SILENT_OUT
export INDENT=$((${INDENT:-1}+$INDENT_SIZE))

$SCRIPTS/package $1

for p in $PKG_RUN_DEPENDS; do
  $SCRIPTS/install $p
done

if [ -f $PACKAGE ]; then
  $ROOT/$TOOLCHAIN/bin/opkg --offline-root $ROOTFS \
                            install $PACKAGE >&$VERBOSE_OUT

  # opkg installs the control file with the same timestamp of the package
  # this breaks our scripts, so we touch the control file to make sure it's
  # more recent than the package
  touch $STAMP
fi

exit 0
